Rya*_*uck 3 google-bigquery google-oauth google-cloud-iam
我可以使用服务帐户从本机 BigQuery 表中获取数据。
\n\nselect
但是,当我尝试使用同一服务帐户从 BigQuery 中基于 Google Sheets 的表中获取数据时,我遇到了错误。
from google.cloud import bigquery\n\nclient = bigquery.Client.from_service_account_json(\n json_credentials_path=\'creds.json\',\n project=\'xxx\',\n)\n\n# this works fine\nprint(\'test basic query: select 1\')\njob = client.run_sync_query(\'select 1\')\njob.run()\nprint(\'results:\', list(job.fetch_data()))\nprint(\'-\'*50)\n\n# this breaks\nprint(\'attempting to fetch from sheets-based BQ table\')\njob2 = client.run_sync_query(\'select * from testing.asdf\')\njob2.run()\n
Run Code Online (Sandbox Code Playgroud)\n\n输出:
\n\n\xe2\x9a\xa1 ~/Desktop \xe2\x9a\xa1 python3 bq_test.py\ntest basic query: select 1\nresults: [(1,)]\n--------------------------------------------------\nattempting to fetch from sheets-based BQ table\nTraceback (most recent call last):\n File "bq_test.py", line 16, in <module>\n job2.run()\n File "/usr/local/lib/python3.6/site-packages/google/cloud/bigquery/query.py", line 381, in run\n method=\'POST\', path=path, data=self._build_resource())\n File "/usr/local/lib/python3.6/site-packages/google/cloud/_http.py", line 293, in api_request\n raise exceptions.from_http_response(response)\ngoogle.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.\n
Run Code Online (Sandbox Code Playgroud)\n\n我尝试使用oauth2client.service_account.ServiceAccountCredentials
for 显式定义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.\n
Run Code Online (Sandbox Code Playgroud)\n\n我的理解是,身份验证现在是通过 IAM 处理的,但我没有看到任何适用于该服务帐户的与驱动器有关的角色。
\n\n如何使用 BigQuery python 客户端从工作表支持的表中进行选择?
\n小智 7
我遇到了同样的问题并想出了如何解决它。
在探索google.cloud.bigquery.Client
类时,有一个全局变量元组SCOPE
不会被任何参数或任何Credentials
对象更新,将其默认值保留到使用它的类中。
要解决此问题,您只需向元组添加新的范围 URL 即可google.cloud.bigquery.Client.SCOPE
。
在以下代码中,我将 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',
)
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,您将能够从 BigQuery 中基于表格的表中查询数据。
希望能帮助到你!
归档时间: |
|
查看次数: |
1786 次 |
最近记录: |