2016-02-02 32 views
6

我試圖通過BigQuery API使用Python連接到Google BigQuery。設置BigQuery Python CLI的GOOGLE_APPLICATION_CREDENTIALS

我在這裏下面這個頁面: 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。但是,錯誤仍然存​​在。有誰知道這個問題是什麼?

預先感謝您。

回答

1

錯誤消息中提供的鏈接https://developers.google.com/identity/protocols/application-default-credentials表示將環境變量設置爲指向包含JSON服務憑據的失敗。它看起來像你設置一個Python變量。嘗試設置終端的環境變量以指向正確的文件。

如果您沒有在GCE容器中運行,如oauth2client.client.SignedJwtAssertionCredentials並將其直接指向您的客戶端機密,那麼您可以明確使用其他憑據,因此您不必通過環境變量進行間接訪問。

8

它正在您的本地UNIX(或其他)環境中查找環境變量,而不是您的python腳本中的變量。

您可以設定:通過打開您的終端或Cygwin和執行下列操作之一:

export GOOGLE_APPLICATION_CREDENTIALS='/path/to/your/client_secret.json' 

鍵入到你的終端設置變量爲此會話

打開你的.bashrc文件,在UNIX由納米〜/ .bashrc中鍵入這行添加到它的用戶特定的別名之下,如果你看到一個標題:

GOOGLE_APPLICATION_CREDENTIALS="/full/path/to/your/client_secret.json" 

然後鍵入源碼重新裝入e〜/ .bashrc並通過嘗試echo $GOOGLE_APPLICATION_CREDENTIALS確認它已被設置。如果它返回的路徑,你很好。

+0

感謝這個作品。 – geekidharsh

0

它正在尋找環境變量。但是我可以使用Application Default Credentials在Windows平臺上解決這個問題。

的步驟,我跟着:

  • 安裝谷歌SDK
  • 然後執行gcloud init步驟指定默認我的證書和默認的項目,該項目需要,當你可以改變。 gcloud可執行文件可以在您選擇安裝Google SDK的bin目錄中生效。
  • 成功提供憑證後,您可以在C:\Users\"yourusername"\AppData\Roaming\gcloud\legacy_credentials\"youremail" 的位置辦理登機手續。您可以在那裏找到以JSON格式存儲的憑據。

它幫助我解決了錯誤。

11

首先 - 感謝代碼 - 這提供了非常有用的。 我也建議直接在你的代碼中添加設置環境變量 - 不要爲你工作的每個環境設置它。 您可以使用下面的代碼:

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

需要不同的憑據不同的項目之間切換時,我發現這非常有用。

0

如果你想使用不同的憑證文件,而無需設置環境變量,可以使用下面的代碼:

from oauth2client import service_account 
from apiclient.discovery import build 
import json 

client_credentials = json.load(open("<path to .json credentials>")) 

credentials_token = service_account._JWTAccessCredentials.from_json_keyfile_dict(client_credentials) 

bigquery_service = build('bigquery', 'v2', credentials=credentials_token) 
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'])) 
3

我不知道BigQuery,但我使用Google Data Store保存。如果你已經在你的Mac安裝gcloud sdk,你可以嘗試運行此命令

gcloud auth application-default login 
+0

謝謝!這是唯一對我有效的東西! – mountainclimber

0

GOOGLE_APPLICATION_CREDENTIALS未找到錯誤解C#

System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",@"C:\apikey.json"); 
string Pathsave = System.Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");