Server side:
function doPost(e) {
const FOLDER_ID = '###FOLDER_ID###';
var name = e.parameter.name;
saveFile(e.postData.contents, name, FOLDER_ID);
return 'Success';
}
function saveFile(data, name, id) {
data = Utilities.newBlob(Utilities.base64DecodeWebSafe(data));
DriveApp.getFolderById(id)
.createFile(data.setName(name))
}
Client side:
import requests, base64
url = '###WEB_APP_PUBLISHED_URL###'
name = '###FILENAME###'
requests.post(url + '?name=' + name, data = base64.urlsafe_b64encode(open('##UPLOAD FILE PATH##', 'rb').read()))
gauth = GoogleAuth() drive = GoogleDrive(gauth) from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() drive = GoogleDrive(gauth) upload_file_list = ['1.jpg', '2.jpg'] for upload_file in upload_file_list: gfile = drive.CreateFile({ 'parents': [{ 'id': '1pzschX3uMbxU0lB5WZ6IlEEeAUE8MZ-t' }] }) # Read file and set it as the content of this instance. gfile.SetContentFile(upload_file) gfile.Upload() # Upload the file.
We've imported the necessary modules. The above function was grabbed from the Google Drive quickstart page. It basically looks for token.pickle file to authenticate with your Google account. If it didn't find it, it'd use credentials.json to prompt you for authentication in your browser. After that, it'll initiate the Google Drive API service and return it.,Before we do anything, we need to authenticate our code to our Google account. The below function does that:,You saw the first three lines in previous recipes. We simply authenticate with our Google account and search for the desired file to download.,Remember, whenever you change the SCOPES list, you need to delete token.pickle file to authenticate to your account again with the new scopes. See this page for further information, along with a list of scopes and their explanations.
To get started, let's install the required libraries for this tutorial:
pip3 install google - api - python - client google - auth - httplib2 google - auth - oauthlib tabulate requests tqdm
Before we do anything, we need to authenticate our code to our Google account. The below function does that:
import pickle import os from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from tabulate import tabulate # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'] def get_gdrive_service(): creds = None # The file token.pickle stores the user 's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no(valid) credentials available, let the user log in . if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port = 0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) # return Google Drive API service return build('drive', 'v3', credentials = creds)
Going to the main function, let's define a function that lists files in our drive:
def main(): "" "Shows basic usage of the Drive v3 API. Prints the names and ids of the first 5 files the user has access to. "" " service = get_gdrive_service() # Call the Drive v3 API results = service.files().list( pageSize = 5, fields = "nextPageToken, files(id, name, mimeType, size, parents, modifiedTime)").execute() # get the results items = results.get('files', []) # list all 20 files & folders list_files(items)
We converted that list of dictionaries items variable into a list of tuples rows variable, and then pass them to tabulate module we installed earlier to print them in a nice format, let's call main()
function:
if __name__ == '__main__':
main()
Files:
ID Name Parents Size Type Modified Time
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
1 FaD2BVO_ppps2BFm463JzKM - gGcEdWVT some_text.txt['0AOEK-gp9UUuOUk9RVA'] 31.00 B text / plain 2020 - 05 - 15 T13: 22: 20.000 Z
1 vRRRh5OlXpb - vJtphPweCvoh7qYILJYi google - drive - 512. png['0AOEK-gp9UUuOUk9RVA'] 15.62 KB image / png 2020 - 05 - 14 T23: 57: 18.000 Z
1 wYY_5Fic8yt8KSy8nnQfjah9EfVRDoIE bbc.zip['0AOEK-gp9UUuOUk9RVA'] 863.61 KB application / x - zip - compressed 2019 - 08 - 19 T09: 52: 22.000 Z
1 FX - KwO6EpCMQg9wtsitQ - JUqYduTWZub Nasdaq 100 Historical Data.csv['0AOEK-gp9UUuOUk9RVA'] 363.10 KB text / csv 2019 - 05 - 17 T16: 00: 44.000 Z
1 shTHGozbqzzy9Rww9IAV5_CCzgPrO30R my_python_code.py['0AOEK-gp9UUuOUk9RVA'] 1.92 MB text / x - python 2019 - 05 - 13 T14: 21: 10.000 Z
You can do this by publishing a web app anycodings_google-apps-script to run as "Me"(you) with access: anycodings_google-apps-script "Anyone, even anonymous".,I don't want to do this with API because anycodings_python it's with JSON file and requesting a anycodings_python password to google account.,I want to create a script in google script anycodings_python that will upload the file to the site.,I want to send from the Python file without anycodings_python a JSON file and without requesting a google anycodings_python account.
I found how to do it with html:
function saveFile(data, name, folderName) {
var contentType = data.substring(5, data.indexOf(';'));
var file = Utilities.newBlob(
Utilities.base64Decode(data.substr(data.indexOf('base64,') + 7)),
contentType,
name
); //does the uploading of the files
DriveApp.getFolderById(childFolderIdA).createFile(file);
}
Server side:
function doPost(e) {
const FOLDER_ID = '###FOLDER_ID###';
var name = e.parameter.name;
saveFile(e.postData.contents, name, FOLDER_ID);
return 'Success';
}
function saveFile(data, name, id) {
data = Utilities.newBlob(Utilities.base64DecodeWebSafe(data));
DriveApp.getFolderById(id)
.createFile(data.setName(name))
}
Client side:
import requests, base64
url = '###WEB_APP_PUBLISHED_URL###'
name = '###FILENAME###'
requests.post(url + '?name=' + name, data = base64.urlsafe_b64encode(open('##UPLOAD FILE PATH##', 'rb').read()))
gauth = GoogleAuth() drive = GoogleDrive(gauth) from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive gauth = GoogleAuth() drive = GoogleDrive(gauth) upload_file_list = ['1.jpg', '2.jpg'] for upload_file in upload_file_list: gfile = drive.CreateFile({ 'parents': [{ 'id': '1pzschX3uMbxU0lB5WZ6IlEEeAUE8MZ-t' }] }) # Read file and set it as the content of this instance. gfile.SetContentFile(upload_file) gfile.Upload() # Upload the file.