首页 > 解决方案 > 通过 Google Cloud Function (Python) 从 BigQuery 数据库连接和查询

问题描述

我有

  1. 一个谷歌云函数(main.py + requirements.txt)
  2. bigQuery 数据库
  3. 工作查询

有人可以帮助我提供链接/教程/代码,以使用我在 Python 中的 Google Cloud Function 连接到这个 bigquery 数据库,并简单地从数据库中查询一些数据并显示它。

我尝试了https://cloud.google.com/bigquery/docs/reference/libraries但它与从正常部署连接到大查询有关,而不是 Google Cloud 功能。

这就是我到目前为止所拥有的。它正在部署没有错误,但在测试时,它给出了 500 错误

main.py(示例公共查询

from google.cloud import bigquery

def query_stackoverflow(request):
 client = bigquery.Client()
 query_job = client.query(
    """
    SELECT
      CONCAT(
        'https://stackoverflow.com/questions/',
        CAST(id as STRING)) as url,
      view_count
    FROM `bigquery-public-data.stackoverflow.posts_questions`
    WHERE tags like '%google-bigquery%'
    ORDER BY view_count DESC
    LIMIT 10"""
)

results = query_job.result()  # Waits for job to complete.
return Response("{'message':'successfully connected'}", status=200, mimetype='application/json')

要求.txt

google-cloud-bigquery

错误日志:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your 
request. Either the server is overloaded or there is an error in the 
application.</p>

标签: python-3.xflaskgoogle-bigquerygoogle-cloud-functions

解决方案


  1. 创建一个服务帐户并授予必要的角色。
gcloud iam service-accounts create connect-to-bigquery
gcloud projects add-iam-policy-binding your-project --member="serviceAccount:connect-to-bigquery@your-project.iam.gserviceaccount.com" --role="roles/owner"
  1. 使用您刚刚创建的服务帐户作为身份创建云功能 在此处输入图像描述

  2. 编辑 main.py 和 requirements.txt

在此处输入图像描述 在此处输入图像描述

  1. 部署和测试功能 在此处输入图像描述 在此处输入图像描述

成功!


推荐阅读