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

How to use google drive API without web browser

我正在编写一个 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'}

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

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

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