1

尝试使用Oauth 2.0 服务器到服务器身份验证(使用服务帐户)将文件上传到谷歌驱动器。使用他们的示例代码作为参考,生成的脚本是这样的:

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 收到“您需要许可”消息,这很奇怪,因为我已登录到创建服务帐户的帐户。

4

1 回答 1

1

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

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

于 2013-09-24T23:33:51.050 回答