【问题标题】:Automate Google Drive SDK Authorization自动化 Google Drive SDK 授权
【发布时间】:2013-11-08 18:10:03
【问题描述】:

我遇到了一个问题。

#!/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)

上面的代码要求用户将url复制到浏览器,然后授权他们的帐户,然后再次复制粘贴代码并将其粘贴到终端上。我知道存储凭据并使用刷新令牌,用户只需要这样做一次。

但是,我不想要太多的用户交互。用户是否可以通过登录他们的 gmail 帐户进行授权?从我的代码本身来看,授权链接应该在没有用户做的情况下在网络浏览器中打开,并且只需登录到他/她的帐户,就是这样,授权完成,并且此登录也应该只发生一次一次授权,这样无论上传什么,都会上传到他的 Google Drive 帐户并进行维护。授权码应该直接取回,这些凭证应该照常存储和使用,令牌也应该刷新。

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

谁能帮我解决这个问题?如果使用上面的代码,那么我应该怎么做才能使任务自动化?如果使用服务帐户,我应该怎么做才能让应用将数据上传到用户自己的驱动器帐户?

任何帮助将不胜感激。

谢谢!

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 嘿,我正在自动执行任务.. 用户将在他们的系统上安装这个应用程序......它类似于新的 Dropbox 测试版......
    【解决方案2】:

    对 DropBox 做了同样的事情。您可以集成 PyQt 或 PySide QWebView (Webkit),您可以在其中放置自动打开 URL。混合使用 javascript 和 python 可以完成这项工作。

    【讨论】:

    • 嘿,感谢您恢复...但是,我怎样才能直接获得验证码呢?
    • 您可以访问其中的完整页面和数据。您可以自动化整个过程。只需尝试 PyQt/Pyside 的简单 QWebView 示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多