繁体   English   中英

如何使用 Python 从 TOML 文件中读取 Google API 凭据?

[英]How do I read Google API credentials from a TOML file with Python?

我正在尝试使用 Google 表格 Api 提取一些数据。 这是代码的开头:


# Import the python libraries.
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from pathlib import Path
import os
import json


# Get JSON_DATA from the build environment.
jsondict = json.loads(os.environ['JSON_DATA'])

# Use creds to create a client to interact with the Google Drive API
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_dict(jsondict, scope)
client = gspread.authorize(creds)

# Open the Google Sheet by ID.
sheet1 = client.open_by_key("somekey").sheet1

# Extract all of the records for each row.
sheetdata1 = sheet1.get_all_records()

在我所指的教程中,这就是作者对JSON_DATA object 所说的话:

注意:python 代码中的“JSON_DATA”变量是一个 Netlify 构建环境变量,我使用 JSON 格式 Google API 设置了我的脚本凭据信息以保密。

我的netlify.toml ,其中包含构建环境变量有这个:

[build]
command = "hugo"
publish = "public"
[build.environment]
HUGO_VERSION = "0.80.0"

[context]
[context.branch-deploy]
command = "hugo -F -b $DEPLOY_PRIME_URL"
[context.deploy-preview]
command = "hugo -F -b $DEPLOY_PRIME_URL"
[context.production]
[context.production.environment]
HUGO_ENV = "production"

我知道要包含从 Google 下载的凭据(在 JSON 文件中),我必须将其放入netlify.toml

[installed]
client_id = "something.apps.googleusercontent.com"
project_id = "someiD"
auth_uri = "https://accounts.google.com/o/oauth2/auth"
token_uri = "whatevergoeshere"
client_secret = "somesecret"
redirect_uris = [ "something", "http://localhost" ]

但是如何阅读这些 Python 代码的凭据? 该行似乎表明它只需要 JSON 文件。

JSON_DATA object 仅包含比从 Google 收到的凭据 object 更多的信息。 但是,需要来自 Google 的凭据的调用方法将简单地忽略它们不需要的其他参数。 因此,只要您保持凭证对象的名称相同,诸如ServiceAccountCredentials.from_json_keyfile_dict()之类的方法将简单地忽略那些它不需要的方法。

好的,所以您需要将 json 密钥文件的内容复制粘贴到实际环境变量本身中:

JSON_DATA = '{"key":"secret"}'

不是最直接的方式,但它有效。

为了保持理智,我将使用 web 接口来处理这些变量。

https://docs.netlify.com/configure-builds/environment-variables/

第一行将环境变量中的任何内容解析为字典。 在这种情况下,不需要解析 toml 本身,因为它已经为您解析过了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM