【问题标题】:Files uploaded using Oauth 2.0 service account do not appear不显示使用 Oauth 2.0 服务帐户上传的文件
【发布时间】:2013-09-24 22:47:05
【问题描述】:

尝试使用Oauth 2.0 server to server authentication(使用service account)将文件上传到谷歌驱动器。使用了他们的示例代码作为参考,生成的脚本是这样的:

import httplib2
import pprint
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
from apiclient.http import MediaFileUpload

def main(argv):
    # Load the key in PKCS 12 format that you downloaded from the Google API
    # Console when you created your Service account.
    f = open('key.p12', 'rb')
    key = f.read()
    f.close()

    # Check https://developers.google.com/drive/scopes for all available scopes
    OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'

    # Path to the file to upload
    FILENAME = 'testfile.txt'

    # Create an httplib2.Http object to handle our HTTP requests and authorize it
    # with the Credentials. Note that the first parameter, service_account_name,
    # is the Email address created for the Service account. It must be the email
    # address associated with the key that was created.
    credentials = SignedJwtAssertionCredentials(
        'xxxxx-xxxxxxx@developer.gserviceaccount.com',
        key,
        OAUTH_SCOPE)
    http = httplib2.Http()
    http = credentials.authorize(http)

    drive_service = build('drive', 'v2', http=http)

    # Insert a file
    media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True)
    body = {
        'title': 'My document',
        'description': 'A test document',
        'mimeType': 'text/plain'
    }

    fil = drive_service.files().insert(body=body, media_body=media_body).execute()
    pprint.pprint(fil)

if __name__ == '__main__':
main(sys.argv)

脚本似乎运行正常(没有错误,pprint 显示的输出似乎很好)。但是,该帐户的谷歌驱动器页面不显示上传的文件。当尝试从 pprint 输出访问其中一个链接以查看文件时,我从 Google Drive 收到“您需要许可”消息,这很奇怪,因为我已登录到创建服务帐户的帐户。

【问题讨论】:

    标签: oauth-2.0 google-drive-api google-api-python-client


    【解决方案1】:

    该文件归服务帐户所有,而不是您的 Google 帐户。服务帐户有自己的 5GB 空间用于 Google 云端硬盘。

    您需要与您的用户帐户共享文件或拥有服务帐户impersonate your user account(假设您在 Google Apps 域中),以便该文件由您的用户帐户创建和拥有。

    【讨论】:

    • 我只想使用脚本将文件上传到驱动器帐户,而无需每次都需要授权(并且无需将用户名和密码放入脚本中)。我没有使用 Google Apps。我运气不好?
    • 不,您并没有走运,只需使用普通的 OAuth 2.0 Web 流程,您只需执行一次流程,它将存储一个刷新令牌,之后每次都会使用该令牌那。最简单的入门方法是使用developers.google.com/quickstart,选择 Drive API 和 Python|Command-Line 平台,它将创建一个您想要的框架应用程序,只需添加您的 service.files().insert( ...) 将上面的代码添加到生成的骨架中。
    • 相关的 Python 快速入门指南在这里:developers.google.com/drive/web/quickstart/quickstart-python
    猜你喜欢
    • 2021-06-22
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 2015-04-03
    相关资源
    最近更新 更多