[英]PyDrive and Google Drive - automate verification process?
我正在嘗試使用PyDrive使用本地Python腳本將文件上傳到Google雲端硬盤,我希望它能自動運行,因此它可以通過cron作業每天運行。 我已在本地的settings.yaml文件中存儲了Google雲端硬盤應用的客戶端OAuth ID和密碼,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
您可以(應該)創建一個服務帳戶 - 使用來自Google API控制台的ID和私鑰 - 這不需要重新驗證,但您需要保密私鑰。
基於google 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和key與以前相同:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.