python google drive api to sync folder

Solutions on MaxInterview for python google drive api to sync folder by the best coders in the world

showing results for - "python google drive api to sync folder"
Jennifer
21 Apr 2018
1#pip install --upgrade google-api-python-client oauth2client
2from __future__ import print_function
3
4import os
5import glob
6
7from googleapiclient.discovery import build
8from googleapiclient.http import MediaFileUpload
9from httplib2 import Http
10from oauth2client import file as oauth2file, client, tools
11
12SCOPES = 'https://www.googleapis.com/auth/drive'
13CREDENTIAL_FILE = 'gdrive_sync_credential.json'
14TOKEN_FILE = 'gdrive_sync_token.json'
15
16def sync_folder(local_folder, gdrive_folder_name):
17    store = oauth2file.Storage(TOKEN_FILE)
18    creds = store.get()
19    if not creds or creds.invalid:
20        flow = client.flow_from_clientsecrets(CREDENTIAL_FILE, SCOPES)
21        creds = tools.run_flow(flow, store)
22    service = build('drive', 'v3', http=creds.authorize(Http()))
23    drive_service = service
24
25    file_metadata = {
26        'name': gdrive_folder_name,
27        'mimeType': 'application/vnd.google-apps.folder'
28    }
29
30    response = drive_service.files().list(q="name='{name}' and mimeType='{mimeType}'".format(name=file_metadata['name'], mimeType=file_metadata['mimeType'])).execute()
31    items = response.get('files', [])
32    if not items:
33        print("'{0}'' not found, create new".format(file_metadata['name']))
34        file = drive_service.files().create(body=file_metadata,
35                                            fields='id').execute()
36    else:
37        print("'{0}'' found".format(file_metadata['name']))
38        file = items[0]
39
40    folder_id = file.get('id')
41    print("folderId={0}".format(folder_id))
42
43    # check files on gdrive
44    response = drive_service.files().list(q="'{folderId}' in parents".format(folderId=folder_id)).execute()
45    drive_filenames = {}
46    for _file in response.get('files', []):
47        drive_filenames[_file.get('name')] = _file.get('id')
48
49    print("drive_filenames={0}".format(len(drive_filenames)))
50
51    # only upload new files
52    for _file in glob.glob(local_folder + '/*.gz'):
53        filename = os.path.basename(_file)
54        if filename not in drive_filenames:
55            print("Upload {0}".format(filename))
56
57            file_metadata = {
58                'name': filename,
59                'parents': [folder_id],
60            }
61            media = MediaFileUpload(_file, mimetype='application/gzip')
62            file = drive_service.files().create(body=file_metadata,
63                                                media_body=media,
64                                                fields='id').execute()
65
66            print("Uploaded: {0}".format(file.get('id')))
67        else:
68            print("{0} Exist".format(filename))
69
70
71    # delete files no longer exist in local
72    for _file, _id in drive_filenames.iteritems():
73        print("Delete '{0}', {1}".format(_file, _id))
74        drive_service.files().delete(fileId=_id).execute()
75