【问题标题】:Connect and query from a BigQuery database via a Google Cloud Function (Python)通过 Google Cloud Function (Python) 从 BigQuery 数据库连接和查询
【发布时间】:2021-04-12 23:19:54
【问题描述】:

我有

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

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

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

这是我目前所拥有的。它正在部署没有错误,但在测试时,它给出了 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')

requirements.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>

【问题讨论】:

  • 有应用日志吗?如果是这样,我可以请您将它们附加到问题中吗?
  • 添加了 500 错误代码。除此之外找不到任何其他日志。
  • 您有 Cloud Logging 的详细信息吗?这里只是 HTTP 响应。
  • 我认为我无权查看此帐户中的这些日志。感谢反馈,问题已解决。

标签: python-3.x flask google-bigquery google-cloud-functions


【解决方案1】:
  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. 部署和测试函数

成功!

【讨论】:

  • 我删除了所有内容,并一一关注您的屏幕。完美运行。
  • 嗨,我有一个错误。 IndentationError: expected an indented block
猜你喜欢
  • 2021-12-30
  • 1970-01-01
  • 2020-01-23
  • 2018-08-16
  • 2018-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-28
相关资源
最近更新 更多