有没有办法通过 JSON 密钥文件本身而不是文件路径进行 Google Cloud Python 身份验证?

Fla*_*air 3 python authentication environment-variables google-cloud-platform

所以对于Ruby来说,你可以将JSON内容设置到 的环境变量中GOOGLE_CLOUD_KEYFILE_JSON。我正在尝试查找 Python 的文档,但我只能看到加载文件路径身份验证的文档。

Fla*_*air 8

我找到了一种方法,但我想知道是否有更好的方法。使用该google-auth库,我可以做这样的事情:

import json

from google.cloud import bigquery
from google.oauth2 import service_account

"""
Securely get content of JSON file from protected memory because having
the credential file plainly on the filesystem is unsafe
"""

service_account_info = json.loads(json_file_content_string)
credentials = service_account.Credentials.from_service_account_info(service_account_info)
client = bigquery.Client(project='secret-proj', credentials=credentials)
Run Code Online (Sandbox Code Playgroud)

有关该库的更多信息: https: //google-auth.readthedocs.io/en/latest/reference/google.oauth2.service_account.html