我可以使用服务帐户从本机BigQuery表中获取数据。
但是,在使用相同的服务帐户从BigQuery中基于Google表格的表格尝试select
时,我遇到了错误。
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.ServiceAccountCredentials
明确定义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.
我的理解是auth现在通过IAM处理,但我没有看到任何适用于此服务帐户的角色与驱动器有任何关系。
如何使用BigQuery python客户端从工作表支持的表中进行选择?
答案 0 :(得分:1)
我遇到了同样的问题,并想出了解决方法。
在探索google.cloud.bigquery.Client
类时,存在一个全局变量元组SCOPE
,该变量元组既不由任何参数也不由任何Credentials
对象进行更新,并将其默认值保留到随后的类中它的用途。
要解决此问题,您只需向google.cloud.bigquery.Client.SCOPE
元组添加一个新的范围URL。
在以下代码中,我向其中添加了Google云端硬盘范围:
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中基于工作表的表中查询数据。
希望有帮助!
答案 1 :(得分: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,作为错误消息建议。