Mat*_*ist 5 python json google-authentication python-requests gspread
我正在设置一个程序来帮助用户完成研究论文的笔记,现在我需要client_secret.json将程序文件与程序文件分开以确保其在线安全。如何从 json 获取凭证而不将其作为 python 程序的文件?
scope = ["https://spreadsheets.google.com/feeds","https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
gs = gspread.authorize(creds)
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,有什么方法可以使用 json 响应而不是 client_secret.json 文件更像:
creds = requests.get("json storage").json
Run Code Online (Sandbox Code Playgroud)
最好的办法是将您的秘密 JSON 的密钥创建为环境变量,并有一个函数返回一个与 json 格式相同的 dict,然后您可以将其与来自_json_keyfile_dict的 auth 方法一起使用
这就是我的做法,以及我如何调用我的环境变量:
def create_keyfile_dict():
variables_keys = {
"type": os.environ.get("SHEET_TYPE"),
"project_id": os.environ.get("SHEET_PROJECT_ID"),
"private_key_id": os.environ.get("SHEET_PRIVATE_KEY_ID"),
"private_key": os.environ.get("SHEET_PRIVATE_KEY"),
"client_email": os.environ.get("SHEET_CLIENT_EMAIL"),
"client_id": os.environ.get("SHEET_CLIENT_ID"),
"auth_uri": os.environ.get("SHEET_AUTH_URI"),
"token_uri": os.environ.get("SHEET_TOKEN_URI"),
"auth_provider_x509_cert_url": os.environ.get("SHEET_AUTH_PROVIDER_X509_CERT_URL"),
"client_x509_cert_url": os.environ.get("SHEET_CLIENT_X509_CERT_URL")
}
return variables_keys
# then the following should work
scope = ["https://spreadsheets.google.com/feeds","https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_dict(create_keyfile_dict(), scope)
gs = gspread.authorize(creds)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2439 次 |
| 最近记录: |