我试图在没有配置文件的情况下验证google API,我甚至找不到证据证明这是可能的,除了在我的服务中的旧代码,多年来没有使用。
我的类收到这个dict.和代码是
self._connection_data = {
"type": args,
"project_id": args,
"private_key_id": args,
"private_key": args,
"client_email": args,
"client_id": args,
"auth_uri": args,
"token_uri": args,
"auth_provider_x509_cert_url": args,
"client_x509_cert_url": args
}
和代码是 -
from google.cloud import bigquery
from google.oauth2 import service_account
def _get_client(self):
credentials = service_account.Credentials.from_service_account_info(self._connection_data)
return bigquery.Client(project=self._project_id, credentials=credentials, location='US')
我收到的错误信息是
'{"error":"invalid_grant","error_description":"Invalid grant: account not found"}
然而,当我使用一个名为config.json的辅助文件和一个操作系统环境变量时,一切都能正常工作。
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = "config.json"
self.job_config = bigquery.QueryJobConfig()
self.job_config.use_legacy_sql = True
return bigquery.Client()
我不想用env变量来解决这个问题 我想使用没有文件路径的Credentials类。
不幸的是,没有其他方法来验证你的API请求,而不是使用环境变量或指定密钥文件路径。有一些方法可以用GCP使用key json文件来验证你的请求。在做任何事情之前,你应该设置你的服务账户,并下载带有你的密钥的json文件,如下所述 此处.
然后,第一种方法是使用默认的凭证,根据。文件:
如果你在构建客户端时没有指定凭证,客户端库会在环境中寻找凭证。
这意味着,你只需要设置你的环境变量。然后,Google客户端库将隐式地确定凭证。此外,它还允许你从你的应用程序中单独提供凭证,这简化了在代码中进行修改的过程。你可以按以下方式设置环境变量。
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"
设置后,你就可以运行下面的程序了 编码:
def implicit():
from google.cloud import storage
# If you don't specify credentials when constructing the client, the
# client library will look for credentials in the environment.
storage_client = storage.Client()
# Make an authenticated API request
buckets = list(storage_client.list_buckets())
print(buckets)
其次,你可以在你的代码中使用 [google.oauth2.service_account][3]
模块。它指出: 文件 的。
OAuth2.0客户端可以识别应用程序 并让终端用户通过谷歌验证您的应用程序。它允许您的应用程序代表最终用户访问谷歌云API。
为了使用该模块,你可以使用两种代码中的一种。
#It creates credentials using your .json file and the Credentials.from_service_account_file constructor
credentials = service_account.Credentials.from_service_account_file(
'service-account.json')
或者
#If you set the environment variable, you can also use
#info = json.loads(os.environ['GOOGLE_APPLICATION_CREDENTIALS_JSON_STRING'])
#Otherwise, you specify the path inside json.load() as below
service_account_info = json.load(open('service_account.json'))
credentials = service_account.Credentials.from_service_account_info(
service_account_info)
最后,我鼓励大家查看一下在《中国电子报》中的认证策略。文件.
最后,我设法使我的代码工作,而不需要任何全局变量或文件路径。我的配置凭证出了点问题......。
这是代码 -
# init class here
self.job_config = bigquery.QueryJobConfig()
self.job_config.use_legacy_sql = True
def _get_client(self):
credentials = service_account.Credentials.from_service_account_info(self._connection_data)
return bigquery.Client(project=self._project_id, credentials=credentials)
# function to get columns
query_job = self._get_client().query(query, job_config=self.job_config)
results = query_job.result(timeout=self._current_timeout)
我唯一缺失的部分是在我所有的查询中发送带有遗留SQL设置为true的QueryJobConfig类。