如何使用Google Drive API v3上传到Python中的共享驱动器?

时间:2019-08-20 21:59:35

标签: python google-drive-api

如何使用Python版本的Google Drive API v3上传到共享驱动器?

1 个答案:

答案 0 :(得分:3)

您只需要向Files: Create请求中添加supportsAllDrives=True

# In case you need background on the credential/scoping code, it was copied from
#   https://developers.google.com/drive/api/v3/quickstart/python
# Basis for upload code from:
#   https://developers.google.com/drive/api/v3/manage-uploads

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient.http import MediaFileUpload

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive']

credentials_json = 'oauth-credentials.json'
credentials_pickle = 'token.pickle'

def get_creds():
    creds = None
    # Obtain OAuth token / user authorization.
    if os.path.exists(credentials_pickle):
        with open(credentials_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(credentials_pickle, 'wb') as token:
            pickle.dump(creds, token)
    return creds


def main():
    creds = get_creds()

    # Build the drive service.
    drive_service = build('drive', 'v3', credentials=creds)

    # Get the drive ID of the first shared drive. You can introspect the
    # 'results' dict  here to get the right shared drive if it's not the first
    # one.
    results = drive_service.drives().list(pageSize=10).execute()
    shared_drive_id = results['drives'][0]['id']

    # Create the request metatdata, letting drive API know what it's receiving.
    # In this example, we place the image inside the shared drive root folder,
    # which has the same ID as the shared drive itself, but we could instead
    # choose the ID of a folder inside the shared drive.
    file_metadata = {
        'name': 'wakeupcat.jpg',
        'mimeType': 'image/jpeg',
        'parents': [shared_drive_id]}

    # Now create the media file upload object and tell it what file to upload,
    # in this case, "wakeupcat.jpg"
    media = MediaFileUpload('/path/to/wakeupcat.jpg', mimetype='image/jpeg')

    # Upload the file, making sure supportsAllDrives=True to enable uploading
    # to shared drives.
    f = drive_service.files().create(
        body=file_metadata, media_body=media, supportsAllDrives=True).execute()

    print("Created file '%s' id '%s'." % (f.get('name'), f.get('id')))


if __name__ == '__main__':
    main()

注意:在撰写本文时,the API指出supportsAllDrives

  

已弃用-请求的应用程序是否同时支持“我的驱动器”和共享驱动器。此参数仅在2020年6月1日之前有效。之后,假定所有应用程序都支持共享驱动器。 (默认值:false)