我们如何在 python 中将 JSON 凭证存储到 ENV 变量中?

2024-03-14

{
    "type": "service_account",
    "project_id": "project_id",
    "private_key_id": "private_key_id",
    "private_key": "-----BEGIN PRIVATE KEY-----\n",
    "client_email": "email",
    "client_id": "id",
    "auth_uri": "uri_auth",
    "token_uri": "token_urin",
    "auth_provider_x509_cert_url": "auth_provider_x509_cert_url",
    "client_x509_cert_url": "client_x509_cert_url"
}

我尝试对 JSON 进行编码和解码,但没有成功

我什至尝试使用 /// 代替“”

所以我使用sheets-api。我想要实现的是从 .env 变量加载 json 文件的路径

scope=['https://spreadsheets.google.com/feeds',
      'https://www.googleapis.com/auth/drive',
      'https://www.googleapis.com/auth/drive.file',
      'https://www.googleapis.com/auth/spreadsheets'
      ]
credentials = ServiceAccountCredentials.from_json_keyfile_name(r"path-for-json-file", scope)
client = gspread.authorize(credentials)

假设您的 JSON 文件是creds.json

信用.json

{
    "type": "service_account",
    "project_id": "project_id",
    "private_key_id": "private_key_id",
    "private_key": "-----BEGIN PRIVATE KEY-----\n",
    "client_email": "email",
    "client_id": "id",
    "auth_uri": "uri_auth",
    "token_uri": "token_urin",
    "auth_provider_x509_cert_url": "auth_provider_x509_cert_url",
    "client_x509_cert_url": "client_x509_cert_url"
}

main.py

import json

data = json.load(open('creds.json'))

f = open(".env", "x")

for key, value in data.items():
    f.write(f"{key.upper()}={value}\n")

将生成 creds.env

TYPE=service_account
PROJECT_ID=project_id
PRIVATE_KEY_ID=private_key_id
PRIVATE_KEY=-----BEGIN PRIVATE KEY-----

CLIENT_EMAIL=email
CLIENT_ID=id
AUTH_URI=uri_auth
TOKEN_URI=token_urin
AUTH_PROVIDER_X509_CERT_URL=auth_provider_x509_cert_url
CLIENT_X509_CERT_URL=client_x509_cert_url

create_keyfile_dict()基本上返回一个名为variable_keys

from dotenv import load_dotenv

load_dotenv()

def create_keyfile_dict():
    variables_keys = {
        "type": os.getenv("TYPE"),
        "project_id": os.getenv("PROJECT_ID"),
        "private_key_id": os.getenv("PRIVATE_KEY_ID"),
        "private_key": os.getenv("PRIVATE_KEY"),
        "client_email": os.getenv("CLIENT_EMAIL"),
        "client_id": os.getenv("CLIENT_ID"),
        "auth_uri": os.getenv("AUTH_URI"),
        "token_uri": os.getenv("TOKEN_URI"),
        "auth_provider_x509_cert_url": os.getenv("AUTH_PROVIDER_X509_CERT_URL"),
        "client_x509_cert_url": os.getenv("CLIENT_X509_CERT_URL")
    }
    return variables_keys

scope=['https://spreadsheets.google.com/feeds',
      'https://www.googleapis.com/auth/drive',
      'https://www.googleapis.com/auth/drive.file',
      'https://www.googleapis.com/auth/spreadsheets'
      ]
credentials = ServiceAccountCredentials.from_json_keyfile_name(create_keyfile_dict(), scope)
client = gspread.authorize(credentials)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我们如何在 python 中将 JSON 凭证存储到 ENV 变量中? 的相关文章

随机推荐