2

我可以使用服务帐户从原生 BigQuery 表中获取数据。

但是,我在尝试select使用同一服务帐户从 BigQuery 中基于 Google 表格的表时遇到错误。

from google.cloud import bigquery

client = bigquery.Client.from_service_account_json(
    json_credentials_path='creds.json',
    project='xxx',
)

# this works fine
print('test basic query: select 1')
job = client.run_sync_query('select 1')
job.run()
print('results:', list(job.fetch_data()))
print('-'*50)

# this breaks
print('attempting to fetch from sheets-based BQ table')
job2 = client.run_sync_query('select * from testing.asdf')
job2.run()

输出:

⚡  ~/Desktop ⚡  python3 bq_test.py
test basic query: select 1
results: [(1,)]
--------------------------------------------------
attempting to fetch from sheets-based BQ table
Traceback (most recent call last):
  File "bq_test.py", line 16, in <module>
    job2.run()
  File "/usr/local/lib/python3.6/site-packages/google/cloud/bigquery/query.py", line 381, in run
    method='POST', path=path, data=self._build_resource())
  File "/usr/local/lib/python3.6/site-packages/google/cloud/_http.py", line 293, in api_request
    raise exceptions.from_http_response(response)
google.cloud.exceptions.Forbidden: 403 POST https://www.googleapis.com/bigquery/v2/projects/warby-parker-1348/queries: Access Denied: BigQuery BigQuery: No OAuth token with Google Drive scope was found.

我尝试使用oauth2client.service_account.ServiceAccountCredentialsfor 显式定义scopes,包括 的范围drive,但尝试这样做时出现以下错误:

ValueError: This library only supports credentials from google-auth-library-python. See https://google-cloud-python.readthedocs.io/en/latest/core/auth.html for help on authentication with this library.

我的理解是,身份验证现在是通过 IAM 处理的,但我看不到任何角色可应用于此服务帐户,这些角色与驱动器有任何关系。

如何使用 BigQuery python 客户端从工作表支持的表中进行选择?

4

2 回答 2

4

我遇到了同样的问题并想出了如何解决它。

在探索google.cloud.bigquery.Client类时,有一个全局变量元组SCOPE不会被任何参数或任何Credentials对象更新,将其默认值持久保存到使用它的类。

为了解决这个问题,您可以简单地向google.cloud.bigquery.Client.SCOPE元组添加一个新的范围 URL。

在以下代码中,我将 Google Drive 范围添加到其中:

from google.cloud import bigquery

#Add any scopes needed onto this scopes tuple.
scopes = (
     'https://www.googleapis.com/auth/drive'
)

bigquery.Client.SCOPE+=scopes

client = bigquery.Client.from_service_account_json(
    json_credentials_path='/path/to/your/credentials.json',
    project='your_project_name',
)

使用上面的代码,您将能够在 BigQuery 中从基于表格的表格中查询数据。

希望能帮助到你!

于 2018-11-09T20:07:16.650 回答
0

我认为您在进行身份验证时需要通过 gdrive 的范围是对的。范围在这里传递https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/core/google/cloud/client.py#L126似乎 BigQuery 客户端缺少这些范围https:// github.com/GoogleCloudPlatform/google-cloud-python/blob/master/bigquery/google/cloud/bigquery/client.py#L117。我建议在 github 上询问,作为一种解决方法,您可以尝试覆盖包括 gdrive 范围在内的客户端凭据,但您需要使用来自 GoogleCloudPlatform/google-auth-library-python 的 google.auth.credentials 而不是 oauth2client,作为错误消息建议。

于 2017-11-22T22:30:18.577 回答