尝试使用Python查询Google BigQuery时出现“需要登录”错误

时间:2015-05-19 15:15:17

标签: python google-bigquery

我想使用Python从本地Linux机器访问BigQuery数据。 来自Google帮助https://cloud.google.com/bigquery/authorization#service-accounts-server的代码可以很好地为我提供数据集列表。但是查询通过服务库发送

SELECT id, name FROM [test_articles.countries] LIMIT 100

因“需要登录”消息而失败:

googleapiclient.errors.HttpError: <HttpError 401 when requesting https://www.googleapis.com/bigquery/v2/projects/myproject/queries?alt=json returned "Login Required">

在BigQuery Web UI中,查询工作正常。对于身份验证,我使用Google开发控制台中的“Google API服务帐户”,并允许“可以编辑”。

这是整个代码

import httplib2

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

# REPLACE WITH YOUR Project ID
PROJECT_ID = "xxxxxx"
# REPLACE WITH THE SERVICE ACCOUNT EMAIL FROM GOOGLE DEV CONSOLE
SERVICE_ACCOUNT_EMAIL = 'xxxxxxx@developer.gserviceaccount.com'

f = file('xxxxx.p12', 'rb')
key = f.read()
f.close()

credentials = SignedJwtAssertionCredentials(
    SERVICE_ACCOUNT_EMAIL,
    key,
    scope='https://www.googleapis.com/auth/bigquery')

http = httplib2.Http()
http = credentials.authorize(http)

service = build('bigquery', 'v2')
datasets = service.datasets()
response = datasets.list(projectId=PROJECT_ID).execute(http)

print('Dataset list:\n')
for dataset in response['datasets']:
  print("%s\n" % dataset['id'])


# SELECT data

query_data = {'query':'
    SELECT id, name FROM [test_articles.countries] LIMIT 100;
'}
query_request = service.jobs()
query_response = query_request.query(projectId=PROJECT_ID, 
    body=query_data).execute()
pp.pprint(query_response)

2 个答案:

答案 0 :(得分:2)

而不是:

service = build('bigquery', 'v2')
datasets = service.datasets()
response = datasets.list(projectId=PROJECT_ID).execute(http)

尝试:

service = build('bigquery', 'v2', http=http)
datasets = service.datasets()
response = datasets.list(projectId=PROJECT_ID).execute()

(在构建服务时使用经过身份验证的http连接)

答案 1 :(得分:2)

确保通过终端登录您的gcloud帐户:

gcloud auth application-default login