我正在使用这个简单的Google API示例:
import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
# Path to the client_secret.json file downloaded from the Developer Console
CLIENT_SECRET_FILE = 'client_secret.json'
# Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly'
# Location of the credentials storage file
STORAGE = Storage('gmail.storage')
# Start the OAuth flow to retrieve credentials
flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE)
http = httplib2.Http()
# Try to retrieve credentials from storage or run the flow to generate them
credentials = STORAGE.get()
if credentials is None or credentials.invalid:
credentials = run(flow, STORAGE, http=http)
# Authorize the httplib2.Http object with our credentials
http = credentials.authorize(http)
# Build the Gmail service from discovery
gmail_service = build('gmail', 'v1', http=http)
鉴于我之前已经完成了OAuth流(在另一个非Python应用程序中),并获得了刷新令牌等。我想跳过本示例的第一部分,手动创建预期的存储文件gmail.storage
或以其他方式创建凭据对象。
问题是,我找不到任何关于此存储文件的预期格式的文档,或者其中应该包含什么,或者如何以任何其他方式实例化凭据对象。很抱歉我不能在这里展示任何作品,但我不知所措。任何正确方向的观点都将不胜感激。
非常简单,显然这很有效:
from oauth2client.client import GoogleCredentials
from oauth2client import GOOGLE_TOKEN_URI
access_token = None
token_expiry = None
token_uri = GOOGLE_TOKEN_URI
user_agent = 'Python client library'
revoke_uri = None
gCreds = GoogleCredentials(
access_token,
client_id,
client_secret,
refresh_token,
token_expiry,
token_uri,
user_agent,
revoke_uri=revoke_uri
)
如下所述:在谷歌云平台的github 中
您也可以使用字符串来设置它。特别是一个json字符串
import json
import os
from google.oauth2 import service_account
from google.cloud import translate
info = json.loads(os.environ['GOOGLE_APPLICATION_CREDENTIALS_JSON_STRING'])
creds = service_account.Credentials.from_service_account_info(info)
# Instantiates a client
translate_client = translate.Client(credentials=creds)
请注意,我在这个例子中使用了谷歌翻译的API,但这是相同的逻辑。
在这个git问题上还有更多的解释:https://github.com/GoogleCloudPlatform/google-cloud-python/issues/4477
您可能对oauth2client.file.Storage
库感兴趣:
from oauth2client.file import Storage
storage = Storage('gmail.storage')
credentials = storage.get()
storage.put(credentials)