2015-05-19 97 views
3

我想使用Python訪問本地Linux機器上的BigQuery數據。 來自Google幫助https://cloud.google.com/bigquery/authorization#service-accounts-server的代碼正常工作,給了我數據集列表。但通過查詢服務庫嘗試使用Python查詢Google BigQuery時出現「需要登錄」錯誤

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 APIs服務帳戶」,並且擁有「可以修改」權限。

這裏是整個代碼

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 = '[email protected]' 

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) 

回答

1

相反的:

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連接)

0

確保lo g通過終端輸入您的gcloud帳戶:

gcloud auth application-default login 
相關問題