3

我已经为 Google Drive 编写了 Python 代码,它将图像文件上传到我的驱动器应用程序。我有三个疑问。这是我的代码:

#!/usr/bin/python

import httplib2
import pprint

from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow
from apiclient import errors
import sys


CLIENT_ID = 'CLIENT_ID'
CLIENT_SECRET = 'CLIENT_SECRET'

OAUTH_SCOPE = ['https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/drive.file']

REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

FILENAME = "filepath/filename.png"

flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
flow.params['access_type'] = 'offline'
flow.params['approval_prompt'] = 'force'
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 = flow.step2_exchange(code)

http = httplib2.Http()
http = credentials.authorize(http)

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

media_body = MediaFileUpload(FILENAME, mimetype='image/png', resumable=True)
body = {
    'title': 'Screen Shot 2013-11-03 at 3.54.08 AM',
    'description': 'A test screenshot',
    'mimeType': 'image/png'
}

file = drive_service.files().insert(body=body, media_body=media_body).execute()

new_permission = {
      'type': 'anyone',
      'role': 'reader'
}

try:
    drive_service.permissions().insert(
        fileId=file['id'], body=new_permission).execute()
except errors.HttpError, error:
    print 'An error occurred: %s' % error

pprint.pprint(file)

我的查询:

  1. 该程序会将所有图像上传到我给定的 client_id 和 client_secret。
    如何让用户使用我的应用并将他们的图片上传到他们自己的 Google Drive?

  2. 我想自动化这个任务。每当我在终端中运行此应用程序时,它总是要求我提供我不想要的授权码。这可以绕过吗?

  3. 我阅读了有关 refresh_tokens 的信息,但找不到如何在我的应用程序中实现此功能以自动授权。
    那么,refresh_tokens 是否用于此目的?如果是,那么我如何在我的程序中实现它?
    如果没有,那么我如何确保在加载我的应用程序后,该特定文件会直接上传到谷歌驱动器上,无需任何授权,或使用任何自动授权方式,从而完全取消用户交互。

4

1 回答 1

2

“这个程序会将所有图像上传到我给定的 client_id 和 client_secret。”

不,它会将图像上传到通过授权流程的帐户的云端硬盘。Client ID 和 Client Secret 标识您的程序,它们不标识特定用户。

“我想自动化这个任务。每当我在终端中运行这个应用程序时,它总是要求我提供我不想要的授权码。这个可以绕过吗?”

将凭据存储在存储中:

https://developers.google.com/api-client-library/python/guide/aaa_oauth#storage

oauth2client 库为您处理刷新令牌,您缺少的部分是将凭据存储在存储中。用户第一次仍然需要运行授权过程,但之后它应该可以在没有任何交互的情况下工作。查看 tools.run_flow() 为您处理大部分内容:

http://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.tools-module.html#run_flow

请参阅示例以了解其使用方式:

https://code.google.com/p/google-api-python-client/source/browse/samples/plus/plus.py#32

于 2013-11-05T13:36:08.710 回答