自动化Google Drive SDK授权

时间:2013-11-08 18:10:03

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

我遇到了问题。

#!/usr/bin/python

import httplib2
import pprint

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


# Copy your credentials from the console
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'

# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'

# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

# Path to the file to upload
FILENAME = 'document.txt'

# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, 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 = flow.step2_exchange(code)

# 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
media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True)
body = {
  'title': 'My document',
  'description': 'A test document',
  'mimeType': 'text/plain'
}

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

上述代码要求用户将网址复制到浏览器,然后授权他们的帐户,然后再复制粘贴代码并将其粘贴到终端上。我知道存储凭据并使用刷新令牌,用户必须只执行一次。

但是,我不想要那么多用户交互。用户是否可以通过登录他们的Gmail帐户进行授权?从我的代码本身来看,授权链接应该在Web浏览器中打开而无需用户执行,只需登录到他/她的帐户,就是这样,授权就完成了,这个登录也应该只发生一个时间,如同一次授权,以便上传的内容,上传到他的Google云端硬盘帐户并进行维护。应直接检索授权代码,这些凭证应照常存储并使用,并且还应刷新令牌。

我遇到了Google云端硬盘服务帐户,好消息是用户干预完全消失了,但不好的是,它不允许上传文件的帐户。它会在创建应用程序的驱动器上传文件。

任何人都可以帮我解决这个问题吗?如果使用上面的代码,那么我应该做些什么来自动完成任务呢?如果使用服务帐户,我应该怎么做才能让应用程序将数据上传到用户自己的驱动器帐户?

任何帮助都将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:1)

我猜你有一个本地Python应用程序(不是网络应用程序),你希望能够访问用户的驱动器。没有理由需要在Python应用程序中完成授权。例如,您可以编写一个小型Web应用程序,引导用户完成身份验证过程,然后通过电子邮件向您或用户发送适当的字符串以粘贴到python应用程序中。

答案 1 :(得分:0)

对DropBox也一样。您可以集成PyQt或PySide QWebView(Webkit),您可以在其中自动打开URL。混合使用javascript和python可以完成工作。

相关问题