问题描述
我试图通过BigQuery API使用Python连接到Google BigQuery。
我在此处关注此页:
我的代码如下: p>
import os
导入argparse
$ b从apiclient.discovery导入build $ b $ from apiclient .errors从oauth2client.client导入HttpError
导入GoogleCredentials
GOOGLE_APPLICATION_CREDENTIALS ='./Peepl-cb1dac99bdc0.json'
def main(project_id):
#从环境中获取应用程序的默认凭据。
credentials = GoogleCredentials.get_application_default()
print(凭证)
#构造服务对象以与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,
ody = query_data).execute()
print( 'Query Results:')
for query_response ['rows']:
print('\t'.join(field ['v'] for field ['f']) )
,除了HttpError,因为err:
print('Error:{}'。format(err.content))
raise err
if __name__ =='__main__':
parser = argparse.ArgumentParser(
description = __ doc__,
forma tter_class = argparse.RawDescriptionHelpFormatter)
parser.add_argument('project_id',help ='您的Google Cloud Project ID')
args = parser.parse_args()
main(args.project_id)
但是,当我通过终端运行这段代码时,出现以下错误:
oauth2client.client.ApplicationDefaultCredentialsError:应用程序默认凭证不可用。如果在Google Compute Engine中运行,则它们可用。否则,必须定义环境变量GOOGLE_APPLICATION_CREDENTIALS,指向定义凭据的文件。有关更多信息,请参阅https://developers.google.com/accounts/docs/application-default-credentials。
正如您在代码中看到的,我试图设置 GOOGLE_APPLICATION_CREDENTIALS
根据错误中的链接。但是,错误仍然存在。有谁知道这个问题是什么?
预先感谢您。
首先 - 感谢代码 - 这提供了非常有用的功能。
我也建议直接在你的代码中添加设置环境变量 - 不要为你工作的每个环境设置环境变量。
您可以使用以下代码:
import os
os.environ [GOOGLE_APPLICATION_CREDENTIALS] = path_to_your_.json_credential_file
当在需要不同证书的不同项目之间切换时, p>
I'm trying to connect to Google BigQuery through the BigQuery API, using Python.
I'm following this page here:https://cloud.google.com/bigquery/bigquery-api-quickstart
My code is as follows:
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)
However, when I run this code through the terminal, I get the following error:
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.
As you can see in the code, I've tried to set the GOOGLE_APPLICATION_CREDENTIALS
as per the link in the error. However, the error persists. Does anyone know what the issue is?
Thank you in advance.
First - Thanks for the code - this provided to be very useful.I would also suggest adding setting the environmental variable directly in your code - as not to set it for every environment you work on.you can use the following code:
import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "path_to_your_.json_credential_file"
I found this useful when switching between different projects that require different credentials.
这篇关于为BigQuery Python CLI设置GOOGLE_APPLICATION_CREDENTIALS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!