如何在没有网络浏览器的情况下使用google drive API

时间:2015-06-27 18:56:44

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

我正在编写一个python脚本,试图将所有需要的配置文件从我的Linux VM备份到Google Drive Cloud。我想自动执行此操作,而不是每次脚本启动时都从浏览器输入验证码。你能告诉我怎么做吗?

#!/usr/bin/python

import httplib2
import pprint
import credentials as cred
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError

# Path to the file to upload
FILENAME = 'hello.py'

# Run through the OAuth flow and retrieve credentials from credentials.py


def api_upload(FILENAME):

    flow = OAuth2WebServerFlow(cred.credentials['CLIENT_ID'], cred.credentials['CLIENT_SECRET'],
                               cred.credentials['OAUTH_SCOPE'],
                               redirect_uri=cred.credentials['REDIRECT_URI'])

    authorize_url = flow.step1_get_authorize_url()
    print 'Go to the following link in your browser: ' + authorize_url
    code = raw_input('Enter verification code: ').strip()

    credentials = ''
    try:
        credentials = flow.step2_exchange(code)
    except FlowExchangeError:
        print "Your verification code is incorrect or something else is broken."
        exit(1)

    # Create an httplib2.Http object and authorize it with our credentials
    http = httplib2.Http()
    http = credentials.authorize(http)

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

    # Insert a file
    try:
        media_body = MediaFileUpload(FILENAME, mimetype='text/plain',     resumable=True)
        body = {
            'title': "" + FILENAME,
            'description': 'A test document',
            'mimeType': 'text/plain'
        }
        upload_file = drive_service.files().insert(body=body, media_body=media_body).execute()
        pprint.pprint(upload_file)
    except IOError:
        print "No such file"
        exit(1)

# Function usage:
api_upload(FILENAME)

这是我的示例函数。

另一个文件存储请求的凭据:

credentials = {"CLIENT_ID": 'blablabla',
               "CLIENT_SECRET": 'blablabla',
               "OAUTH_SCOPE": 'https://www.googleapis.com/auth/drive',
               "REDIRECT_URI": 'urn:ietf:wg:oauth:2.0:oob'}

1 个答案:

答案 0 :(得分:1)

基本上,您希望将此脚本分成两个单独的脚本,一个用于获取代码并将其交换为访问令牌,另一个使用访问令牌来访问您的Google云端硬盘。我将上面的代码分成两个块,并进行了以下更改。

在第一部分中,您可以像上面那样继续操作,但在初始查询中获取代码时,请将access_type设置为“offline”并将approval_prompt设置为“force”(请参阅​​https://developers.google.com/identity/protocols/OAuth2WebServer)。如果这样做,那么当您交换代码时,返回的令牌将不仅包含access_token,还包含可用于无限刷新访问令牌的refresh_token。那么第一个脚本应该将这些令牌保存到文件并退出。如果你可以使这个工作,那么你只需要运行一点代码(通过其手动干预)一次。

然后,您的第二个脚本可以在需要运行时从文件中加载这些已保存的令牌,并且无需您进行干预即可访问您的文档。