使用Oauth 2.0服务帐户上传的文件不会出现

时间:2013-09-24 22:47:06

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

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

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显示输出似乎没问题)。但是,该帐户的Google云端硬盘页面未显示上传的文件。当尝试从pprint输出访问其中一个链接以查看该文件时,我收到来自Google云端硬盘的“您需要权限”消息,这很奇怪,因为我已登录到我创建服务帐户的帐户。

1 个答案:

答案 0 :(得分:1)

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

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