Ben*_*n P 4 python google-bigquery
我想使用 Python 对 BigQuery 运行 SQL 查询,我是一个完整的初学者。我已经阅读了“使用 API 创建一个简单的应用程序”页面(https://cloud.google.com/bigquery/create-simple-app-api#bigquery-simple-app-build-service-python)并获得了我的代码如下:
from google.cloud import bigquery
client = bigquery.Client()
query_job = client.query("""
#standardSQL
SELECT date, totals.visits AS visits
FROM `myproject.mydataset.ga_sessions_20180111`
GROUP BY date
""")
results = query_job.result() # Waits for job to complete.
for row in results:
print("{}: {}".format(row.title, row.unique_words))
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我收到错误: OSError: Project was not passed and could not be determined from the environment.
阅读这个我认为这个问题与身份验证有关client = bigquery.Client()- 有人可以简单地向我解释这是如何工作的吗?如果我已经登录,它会查找我的身份验证详细信息吗?如果我有多个项目的许可,我是否需要指定我正在与哪个项目合作?
为了对任何 GCP API 进行身份验证,建议使用服务帐户凭据,文档将教您如何创建和下载凭据。
在这一步之后,你应该有一个如下所示的 json 文件:
{
"type": "service_account",
"project_id": "your project",
"private_key_id": "your private key id",
"private_key": "private key",
"client_email": "email",
"client_id": "client id",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/email_id"
}
Run Code Online (Sandbox Code Playgroud)
之后,您可以将文件路径导出到env操作系统中的变量,如下所示:
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json
Run Code Online (Sandbox Code Playgroud)
或者您可以在自己的脚本中直接使用 json 文件构建客户端:
import google.cloud.bigquery as bq
client = bq.Client.from_service_account_json("path/to/key.json")
Run Code Online (Sandbox Code Playgroud)
在project_id将自动为您进行处理,以及(给你创建的JSON文件的项目)。
您询问使用您自己的用户凭据,我不确定如何使用这些凭据进行身份验证,但仍然不建议这样做,您必须管理google.auth并手动构建 OAuth2 步骤,所有这些都已自动完成您在服务帐户中。