通过BigQuery python api查询联合表(Google Drive)

时间:2018-02-07 20:28:05

标签: python google-bigquery gcloud

(这里有很多类似的线程但不幸的是我无法在这里或Goolge找到我的错误的答案)

我正在尝试在BigQuery中查询指向Drive中的电子表格的联合表。

我运行以下命令为gcloud创建默认应用程序凭据:

$ gcloud auth application-default login

但是这不包括驱动器进入范围所以我收到以下错误消息(这是有道理的):禁止:403拒绝访问:BigQuery BigQuery:找不到具有Google Drive范围的OAuth令牌。

然后我尝试使用显式驱动器范围进行身份验证:

$ gcloud auth application-default login --scopes=https://www.googleapis.com/auth/drive,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/bigquery

之后,当我尝试使用bigquery python api时,我收到以下错误:

“禁止访问:403访问被拒绝:BigQuery BigQuery:未配置访问权限。项目764086051850之前尚未使用Drive API或已禁用。通过访问https://console.developers.google.com/apis/api/drive.googleapis.com/overview?project=764086051850启用它然后重试。如果您最近启用了此API ,等待几分钟,让行动传播到我们的系统并重试。“

上面的项目编号在我们的组织中不存在,并且提供的链接指向一个页面,其中显示: API“drive.googleapis.com”不存在或您无权访问

默认项目肯定启用了Drive API,因此错误消息没有多大意义。我也可以使用bq query_string命令从终端查询表。

我目前没有关于如何进一步调试这个问题的建议吗?

配置:
Google Cloud SDK 187.0.0
Python 2.7
google-cloud 0.27.0
google-cloud-bigquery 0.29.0

1 个答案:

答案 0 :(得分:1)

使用默认凭据时可能会issues。但是,您可以使用服务帐户,将凭据保存在JSON文件中并添加必要的范围。我做了一个快速测试,这段代码对我有用:

from google.cloud import bigquery
from google.oauth2.service_account import Credentials

scopes = (
        'https://www.googleapis.com/auth/bigquery',
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/drive'
)
credentials = Credentials.from_service_account_file('/path/to/credentials.json')
credentials = credentials.with_scopes(scopes)
client = bigquery.Client(credentials=credentials)

query = "SELECT * FROM dataset.federated_table LIMIT 5"
query_job = client.query(query)
rows = query_job.result()
for row in rows: print(row)

如果您收到404未找到错误,则是因为您需要与服务帐户共享电子表格(查看权限)