PyDrive与Google Drive - 如何自动化验证过程?
我正在尝试使用PyDrive通过本地的Python脚本将文件上传到Google Drive。我希望这个脚本能够自动化,每天通过定时任务运行。我把Google Drive应用的客户端OAuth ID和密钥存储在本地的settings.yaml文件中,PyDrive会读取这个文件来进行身份验证。
我遇到的问题是,虽然这个方法有时能正常工作,但偶尔它会要求我提供一个验证码(如果我使用CommandLineAuth),或者会打开浏览器让我输入Google账户密码(如果使用LocalWebserverAuth),这样我就没法完全自动化这个过程。
有没有人知道我需要调整哪些设置——无论是在PyDrive还是在Google OAuth那边——才能让这个设置一次性完成,然后以后就能自动运行,而不需要再输入任何信息?
这是settings.yaml文件的样子:
client_config_backend: settings
client_config:
client_id: MY_CLIENT_ID
client_secret: MY_CLIENT_SECRET
save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json
get_refresh_token: False
oauth_scope:
- https://www.googleapis.com/auth/drive.file
1 个回答
9
你可以(其实应该)创建一个服务账号,这个账号需要在谷歌API控制台里生成一个ID和私钥。这样做的话,就不需要重新验证了,但你要确保私钥是保密的。
根据谷歌的Python示例,创建一个凭证对象,然后把它赋值给PyDrive的GoogleAuth()对象:
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
# from google API console - convert private key to base64 or load from file
id = "...@developer.gserviceaccount.com"
key = base64.b64decode(...)
credentials = SignedJwtAssertionCredentials(id, key, scope='https://www.googleapis.com/auth/drive')
credentials.authorize(httplib2.Http())
gauth = GoogleAuth()
gauth.credentials = credentials
drive = GoogleDrive(gauth)
编辑(2016年9月): 对于最新的集成版google-api-python-client(1.5.3),你可以使用以下代码,ID和密钥和之前的一样:
import StringIO
from apiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials
credentials = ServiceAccountCredentials.from_p12_keyfile_buffer(id, StringIO.StringIO(key), scopes='https://www.googleapis.com/auth/drive')
http = credentials.authorize(httplib2.Http())
drive = discovery.build("drive", "v2", http=http)