使用dotenv而不是json-fi的pygsheets

2024-06-16 08:52:28 发布

您现在位置:Python中文网/ 问答频道 /正文

连接到gsheets:通常的方法是使用脚本gsheets.py(下面的文件夹结构)所在的根文件夹中的gc = pygsheets.authorize()文件运行creds.json

├── creds.json
├── gsheets.py

希望使用service_account_env_var而不是使用json文件

那个creds.json文件文件如下所示:

{
    "token": null, 
    "refresh_token": "token", 
    "id_token": null, 
    "token_uri": "token_uri", 
    "client_id": "client_id.apps.googleusercontent.com", 
    "client_secret": "secret"
}

如何使用json文件中的凭据创建.env文件?你知道吗

根据pygsheets文件: pygsheets - Environment variables

This assumes you have set an environment variable key GDRIVE_API_CREDENTIALS set with the value of the Service Account .json file described in the above Service Account section.

不幸的是,没有关于如何设置环境变量的指导。 我在想:

创建.env文件(我真的不知道如何用env文件格式表达json,以便包装单个键:值对在{}…:

# .env
GDRIVE_API_CREDENTIALS = {
token = null
refresh_token = token
id_token = null
token_uri = token_uri
client_id = client_id.apps.googleusercontent.com
client_secret = secret }

创建设置.py地址:

# settings.py

from dotenv import load_dotenv
load_dotenv()

import os
creds = os.getenv('GDRIVE_API_CREDENTIALS')

pygsheets.authorize(service_account_env_var = creds)

当creds作为arg提供给service_account_env_var时,最终结果将是成功的连接


Tags: 文件pyenvclienttokenidjsonsecret
1条回答
网友
1楼 · 发布于 2024-06-16 08:52:28

如果您查看pygsheets代码,您可以看到json.loads文件. 所以在您的例子中,只需将整个json文件作为字符串存储在env变量中。你知道吗

另外请注意,此选项适用于服务文件,您的文件看起来像用户凭据。你知道吗

编辑: 如果您已经完成了身份验证流,那么可以将生成的令牌文件直接用作json并从中创建凭据。没有直接的选项,您必须从中创建凭证对象。https://github.com/nithinmurali/pygsheets/blob/staging/pygsheets/authorization.py#L37请参阅此代码。你知道吗

旅行现在,将更新包括代码样本。你知道吗

相关问题 更多 >