gpt4 book ai didi

python - 为 BigQuery Python CLI 设置 GOOGLE_APPLICATION_CREDENTIALS

转载 作者:IT老高 更新时间:2023-10-28 20:29:29 24 4
gpt4 key购买 nike

我正在尝试使用 Python 通过 BigQuery API 连接到 Google BigQuery。

我在这里关注这个页面: https://cloud.google.com/bigquery/bigquery-api-quickstart

我的代码如下:

import os
import argparse

from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import GoogleCredentials

GOOGLE_APPLICATION_CREDENTIALS = './Peepl-cb1dac99bdc0.json'

def main(project_id):
# Grab the application's default credentials from the environment.
credentials = GoogleCredentials.get_application_default()
print(credentials)
# Construct the service object for interacting with the BigQuery API.
bigquery_service = build('bigquery', 'v2', credentials=credentials)

try:
query_request = bigquery_service.jobs()
query_data = {
'query': (
'SELECT TOP(corpus, 10) as title, '
'COUNT(*) as unique_words '
'FROM [publicdata:samples.shakespeare];')
}

query_response = query_request.query(
projectId=project_id,
body=query_data).execute()

print('Query Results:')
for row in query_response['rows']:
print('\t'.join(field['v'] for field in row['f']))

except HttpError as err:
print('Error: {}'.format(err.content))
raise err


if __name__ == '__main__':
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('project_id', help='Your Google Cloud Project ID.')

args = parser.parse_args()

main(args.project_id)

但是,当我通过终端运行此代码时,我收到以下错误:

oauth2client.client.ApplicationDefaultCredentialsError: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.

正如您在代码中看到的,我已尝试根据错误中的链接设置 GOOGLE_APPLICATION_CREDENTIALS。但是,错误仍然存​​在。有谁知道问题是什么?

提前谢谢你。

最佳答案

首先 - 感谢您提供的代码 - 这非常有用。我还建议直接在您的代码中添加设置环境变量 - 因为不要为您工作的每个环境都设置它。您可以使用以下代码:

import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path_to_your_.json_credential_file"

我发现这在需要不同凭据的不同项目之间切换时很有用。

关于python - 为 BigQuery Python CLI 设置 GOOGLE_APPLICATION_CREDENTIALS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35159967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com