Is there a way for Google Cloud Python Authentication via the JSON keyfile itself and not the file path?

六眼飞鱼酱① 提交于 2021-02-11 06:54:15

问题


So for Ruby, you can set the JSON content into the environmental variable of GOOGLE_CLOUD_KEYFILE_JSON. I am trying to find the documentation for Python, but all I can see is documentation loading the authentication for file path.


回答1:


I found a way to do it, but I want to know if there is a better way. Using the google-auth library, I can do something like this:

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)

More about the library here: https://google-auth.readthedocs.io/en/latest/reference/google.oauth2.service_account.html




回答2:


Nope, you need to set GOOGLE_APPLICATION_CREDENTIALS with a path to the JSON file instead.

See https://cloud.google.com/docs/authentication/getting-started for more details.




回答3:


You should be able to read the environment variables on Python using the following:

import os
print os.environ['GOOGLE_CLOUD_KEYFILE_JSON']


来源:https://stackoverflow.com/questions/52394413/is-there-a-way-for-google-cloud-python-authentication-via-the-json-keyfile-itsel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!