【问题标题】:How do I upload file to google drive using drive API using python?如何使用 python 的驱动器 API 将文件上传到谷歌驱动器?
【发布时间】:2018-11-10 07:42:31
【问题描述】:

我想使用它的 API 将文件上传到谷歌驱动器,我正在使用代码

def newer():
    url= 'https://USERNAME:PASSWORD@www.googleapis.com/upload/drive/v3/files?uploadType=media'
    data='''{{
      "name":"testing.txt",
    }}'''
    response = requests.post(url, data=data)
    print response.text

但是,我收到如下响应错误消息。

{“错误”:{“错误”:[{ “域”:“全球”, “原因”:“authError”, "message": "此 API 不支持 HTTP 基本身份验证", “位置类型”:“标题”, "location": "Authorization" } ], "code": 401, "message": "HTTP Basic Authentication is not supported for this API" } }

还有其他方法可以使用 python 完成我的工作吗?

我是否需要登录谷歌云才能访问 API 以获取身份验证令牌或凭据

【问题讨论】:

    标签: python api google-drive-api


    【解决方案1】:

    简单方法

    首先,使用以下命令安装 google 驱动器库:

    !pip install gdown
    

    加载数据

    复制你的谷歌驱动器(确保你有正确的谷歌链接):

    !gdown https://test_google_url.com
    

    如果需要,解压缩文件:

    !unzip test_file_here.zip
    

    【讨论】:

    • 问题是关于上传而不是下载
    【解决方案2】:

    我终于明白了如何使用 api 将文件上传到谷歌驱动器。

    首先你需要安装 python 库,它提供了使用驱动 api 的方法。 安装库: pip install google-api-python-client 然后代码如下。

    from __future__ import print_function
    from apiclient.discovery import build
    from httplib2 import Http
    from oauth2client import file, client, tools
    from apiclient.http import MediaFileUpload,MediaIoBaseDownload
    import io
    
    # Setup the Drive v3 API
    SCOPES = 'https://www.googleapis.com/auth/drive.file'
    store = file.Storage('credentials.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
        creds = tools.run_flow(flow, store)
    drive_service = build('drive', 'v3', http=creds.authorize(Http()))
    

    上面的代码 sn-p 是创建对象/变量,它允许您使用正确的凭据进入驱动器。这里drive_service 可以做到这一点。

    文件上传代码如下。

    def uploadFile():
        file_metadata = {
        'name': 'fileName_to_be_in_drive.txt',
        'mimeType': '*/*'
        }
        media = MediaFileUpload('Filename_of_your_local_file.txt',
                                mimetype='*/*',
                                resumable=True)
        file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
        print ('File ID: ' + file.get('id'))
    

    文件 ID 很重要,因为如果您想从驱动器下载文件,您需要文件 ID。

    【讨论】:

    • from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
    【解决方案3】:

    为了访问私人用户数据,您需要获得用户的许可。未经我的许可,您不能上传到我的云端硬盘帐户。

    用户名:密码

    被称为basic authentication 并使用登录名和密码谷歌在 2015 年为此关闭。

    现在要访问私人用户数据,您需要使用 Oauth2。

    我建议从Python quickstart开始

    """
    Shows basic usage of the Drive v3 API.
    
    Creates a Drive v3 API service and prints the names and ids of the last 10 files
    the user has access to.
    """
    from __future__ import print_function
    from apiclient.discovery import build
    from httplib2 import Http
    from oauth2client import file, client, tools
    
    # Setup the Drive v3 API
    SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
    store = file.Storage('credentials.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('drive', 'v3', http=creds.authorize(Http()))
    
    # Call the Drive v3 API
    results = service.files().list(
        pageSize=10, fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])
    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print('{0} ({1})'.format(item['name'], item['id']))
    

    【讨论】:

    • 感谢 DalmTo,我需要登录 Google 云平台的 Oauth2 免费试用版吗?
    • 上述代码 DalmTo 中 credential.json 和 client_secret.json 的内容应该是什么
    • 本教程向您展示了如何创建 json。文件。要明确您的问题表明您正在上传到与谷歌云平台无关的谷歌云端硬盘。您将上传文件到验证您的代码的用户的 google drive 帐户。
    • 我了解client_secret.json,但对Credential.json一无所知
    • Credential.json 是应保存用户凭据的文件。如果它没有告诉你做一些你不需要做的事情,请按照教程。
    猜你喜欢
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多