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

标签 python json google-sheets-api toml

我正在尝试使用 Google Sheets 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 的看法。目的:

Note: the ‘JSON_DATA’ variable in the python code is a Netlify build environment variable that I set with JSON format Google API credential information to keep my secret stuff out of the script.


我的 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 key 文件的内容复制粘贴到实际环境变量中:JSON_DATA = '{"key":"secret"}'不是最直接的方法,但它有效。
为了保持理智,我将使用 Web 界面来处理这些变量。
https://docs.netlify.com/configure-builds/environment-variables/
第一行将环境变量中的任何内容解析为 dict。在这种情况下不需要解析 toml 本身,因为它已经为您解析过了。

关于python - 如何使用 Python 从 TOML 文件中读取 Google API 凭据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65576829/

相关文章:

json - 使用新的 Net Core 3.0 Json 时忽略属性

google-sheets - 如何在谷歌电子表格中获取台湾证券交易所指数

google-sheets-api - Google 表格自动填充一列中的空白单元格,并在其上方添加最后一个非空白单元格

javascript - Google 表格,具有服务帐户的 JWT 客户端

javascript - 向 websocket 客户端发送消息时压缩位必须为 0

python - 属性错误 : 'Ui_MainWindow' object has no attribute 'setCentralWidget'

python - 将 django.test.LiveServerTestCase 的 live_server_url 与另一个字符串连接时出现类型错误

Python+Tkinter,如何在独立于tk前端的后台运行?

c# - 如何用c#反序列化JSON文件

json - "fatal error: unexpectedly found nil while unwrapping an Optional value"解析JSON时