我正在编写一个python脚本,试图将所有需要的配置文件从我的Linux虚拟机备份到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 Drive。我将上面的代码分成两块,并进行了以下更改。
在第一部分中,您可以按照上面的操作继续操作,但在获取代码的初始查询中,请将access_type设置为"offline",将approvel_prompt设置为"force"(请参见https://developers.google.com/identity/protocols/OAuth2WebServer)。如果您这样做,那么当您交换代码时,返回的令牌将不仅包含access_token,还包含可用于无限期刷新访问令牌的refresh_token。因此,第一个脚本应该只将这些令牌保存到一个文件中并退出。如果你能做到这一点,那么你只需要运行那部分代码(通过手动干预)一次。
然后,您的第二个脚本可以在需要运行时从文件中加载这些保存的令牌,并在不需要干预的情况下访问您的文档。