Guest User

pydrive python google drive

a guest
Feb 12th, 2021
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.33 KB | None | 0 0
  1. def upload1(file):
  2.     from pydrive.auth import GoogleAuth
  3.     from pydrive.drive import GoogleDrive
  4.  
  5.     settings_path = 'settings.yaml'
  6.     gauth = GoogleAuth(settings_file=settings_path)
  7.  
  8.     gauth.LoadCredentialsFile("mycreds.txt")
  9.     if gauth.credentials is None:
  10.         gauth.LocalWebserverAuth()
  11.     elif gauth.access_token_expired:
  12.         gauth.Refresh()
  13.     else:
  14.         gauth.Authorize()
  15.     gauth.SaveCredentialsFile("mycreds.txt")
  16.  
  17.     drive = GoogleDrive(gauth)
  18.  
  19.     team_drive_id = 'my_team_drive_id1'
  20.     list_file_q = "{'q': \"'" + team_drive_id + "' in parents and trashed=False\", 'supportsAllDrives': True, 'driveId': '" + team_drive_id + "', 'includeItemsFromAllDrives': True, 'corpora': 'drive'}"
  21.     print("list_file_q: \n")
  22.     print(list_file_q)
  23.     print("\n")
  24.     file_list = drive.ListFile(eval(list_file_q)).GetList()
  25.     print("file_list:\n")
  26.     print(file_list)
  27.     print("\n")
  28.     file_id = ""
  29.     try:
  30.         for file1 in file_list:
  31.             print("file title: \n")
  32.             print(file1['title'])
  33.             print(file1['id'])
  34.             print(file)
  35.             print("\n")
  36.             if file1['title'] == file:
  37.                 file_id = file1['id']
  38.                 print("file names do match, thus deleting... \n")
  39.                 file1.Delete()
  40.                 file1.Trash()
  41.                 drive.CreateFile({'id': file1['id']}).Delete()
  42.             else:
  43.                 print("file names do NOT match, thus NOT deleting. \n")
  44.     except:
  45.         pass
  46.     if not file_id:
  47.         print("creating file from scratch... \n")
  48.         f = drive.CreateFile({'parents': [{'kind': 'drive#fileLink', 'teamDriveId': team_drive_id, 'id': team_drive_id}]})
  49.     else:
  50.         print("updating file using existing file_id... \n")
  51.         var_create_file = "{'id': " + file_id + ", 'parents': [{'kind': 'drive#fileLink', 'teamDriveId': " + team_drive_id + ", 'id': " + team_drive_id + "}]}"
  52.         print("var_create_file: \n")
  53.         print(var_create_file)
  54.         print("\n")
  55.         f = drive.CreateFile(eval(var_create_file))
  56.         print("test after create file \n")
  57.     print("before SetContentFile \n")
  58.     f.SetContentFile(file)
  59.     print("after SetContentFile \n")
  60.  
  61.     print("before f.Upload \n")
  62.     f.Upload(param={'supportsTeamDrives': True})
  63.     print("after f.Upload \n")
Advertisement
Add Comment
Please, Sign In to add comment