Skip to main content
 首页 » 编程设计

python之如何在不将 client_secret.json 检查到版本控制的情况下使用 Google API

2024年12月31日11lyhabc

我正在从事一个项目,根据 https://12factor.net/config ,我们不会在代码中使用凭证之类的东西,而是在环境变量中。

我正在研究使用 Google Sheets API 从我们的数据库中整理一些数据并将其放入 Google 表格中。这是来自 https://developers.google.com/sheets/api/quickstart/python 的部分示例脚本:

from __future__ import print_function 
from apiclient.discovery import build 
from httplib2 import Http 
from oauth2client import file as oauth_file, client, tools 
 
# Setup the Sheets API 
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly' 
store = oauth_file.Storage('token.json') 
creds = store.get() 
if not creds or creds.invalid: 
    flow = client.flow_from_clientsecrets('credentials.json', SCOPES) 
    creds = tools.run_flow(flow, store) 
service = build('sheets', 'v4', http=creds.authorize(Http())) 

首先,我不清楚文档中的内容 'token.json'和 'credentials.json'应该在这个例子中。在 API 控制台的“凭据”选项卡中,我下载了一个 client_secret_<long suffix>.json看起来像这样:

{"installed":{"client_id":"[our_client_id]","project_id":"nps-survey-1532981793379","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"[our_client_secret]","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}} 

这个 JSON 文件应该是 'token.json'在此示例中,或 'credentials.json' ?另外,有没有办法实例化有效的 creds通过直接指定客户端密码和客户端 ID,而不是使用此 JSON 文件?

请您参考如下方法:

我最终完成了 Web 应用程序而不是已安装应用程序的 OAuth 2.0 设置,并使用了 google_auth_oauthlib . Flow 对象有一个类方法 from_client_config() 可以像这样使用(参见 https://developers.google.com/identity/protocols/OAuth2WebServer ):

from django.conf import settings 
from django.shortcuts import redirect 
import google.oauth2.credentials 
import google_auth_oauthlib.flow 
 
 
# Client configuration for an OAuth 2.0 web server application 
# (cf. https://developers.google.com/identity/protocols/OAuth2WebServer) 
CLIENT_CONFIG = {'web': { 
    'client_id': settings.GOOGLE_CLIENT_ID, 
    'project_id': settings.GOOGLE_PROJECT_ID, 
    'auth_uri': 'https://accounts.google.com/o/oauth2/auth', 
    'token_uri': 'https://www.googleapis.com/oauth2/v3/token', 
    'auth_provider_x509_cert_url': 'https://www.googleapis.com/oauth2/v1/certs', 
    'client_secret': settings.GOOGLE_CLIENT_SECRET, 
    'redirect_uris': settings.GOOGLE_REDIRECT_URIS, 
    'javascript_origins': settings.GOOGLE_JAVASCRIPT_ORIGINS}} 
 
# This scope will allow the application to manage your calendars 
SCOPES = ['https://www.googleapis.com/auth/calendar'] 
 
 
 
def get_authorization_url(): 
    # Use the information in the client_secret.json to identify 
    # the application requesting authorization. 
    flow = google_auth_oauthlib.flow.Flow.from_client_config( 
        client_config=CLIENT_CONFIG, 
        scopes=SCOPES) 
 
    # Indicate where the API server will redirect the user after the user completes 
    # the authorization flow. The redirect URI is required. 
    flow.redirect_uri = 'http://localhost:8000' 
 
    # Generate URL for request to Google's OAuth 2.0 server. 
    # Use kwargs to set optional request parameters. 
    authorization_url, state = flow.authorization_url( 
        # Enable offline access so that you can refresh an access token without 
        # re-prompting the user for permission. Recommended for web server apps. 
        access_type='offline', 
        # Enable incremental authorization. Recommended as a best practice. 
        include_granted_scopes='true') 
 
    return authorization_url, state 

settings 属性依次通过调用每个相应属性的 os.getenv() 生成。这样就可以从环境变量中获取配置,而不是本地文件。