【问题标题】:How to connect to "Google Cloud BigQuery" public dataset from "Google Cloud functions"如何从“谷歌云功能”连接到“谷歌云 BigQuery”公共数据集
【发布时间】:2019-12-08 21:13:33
【问题描述】:

我修改了“Google Cloud 函数”服务的默认 hello_pubsub (Python3.7) 函数,用于连接到我在“Google Cloud BigQuery”服务中创建的数据集表。但是,经过许多不同的方法,我对如何使这个函数连接到我在 BigQuery 中创建的数据集一无所知。我确信只有函数的 SQLite 代码有错误。有人,请帮助我

我的代码是:

import sqlite3
import base64

def hello_pubsub(event, context):
    """Triggered from a message on a Cloud Pub/Sub topic.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for the event.
    """
    connection = sqlite3.connect("<BigQueryDataset>")
    crsr = connection.cursor()
    crsr.execute("SELECT * FROM `iotcoretutorial-xxxxxx.DHT11.DHT11Data` WHERE temperature > 24") 
    ans= crsr.fetchall()    

    pubsub_message = base64.b64decode(event['data']).decode('utf-8')
    print("Hello "+pubsub_message)
    print(ans)

PS:这里iotcoretutorial-xxxxxx指的是项目ID。我使用 xxxxxx 来隐藏我的项目的身份(请多多包涵!)

简而言之,iotcoretutorial-xxxxxx.DHT11.DHT11Data 是我在“Google Cloud BigQuery”上创建的带有温度和湿度值的表,我想使用 hello_pubsub打印它> 如果温度值 > 24 则运行并执行一些操作

【问题讨论】:

  • 您为什么要尝试使用 sqlite3 库连接到 bigquery 数据集?你应该看看BigQuery Client Libraries
  • 我建议您更改标题。这对您现在没有帮助,将来也不会帮助其他任何人。

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


【解决方案1】:

尝试使用BigQuery Client Libraries。更多文档here too

import base64
from google.cloud import bigquery

def hello_pubsub(event, context):
    """Triggered from a message on a Cloud Pub/Sub topic.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for the event.
    """
    client = bigquery.Client(project="<your-project>")

    query_str = "SELECT * FROM `iotcoretutorial-xxxxxx.DHT11.DHT11Data` WHERE temperature > 24"

    job = client.query(
        query_str,
        # Location must match that of the dataset(s) referenced in the query.
        location="<your-location>"
    )
    #Wait for job to finish
    job.result()
    #Get results as a dataframe
    #This requires pandas
    #You can do something different with your results here if you want
    ans_df = job.to_dataframe()

    pubsub_message = base64.b64decode(event['data']).decode('utf-8')
    print("Hello " + pubsub_message)
    print(ans_df)

【讨论】:

  • 只是为了通知!我们需要在需求.txt中添加以下语句**google-cloud-bigquery = &lt;version&gt;**((在我的情况下版本是1.17.0))
  • 是的,如果您正在使用该库,则需要将该库添加到您的requirements.txt
  • 你能告诉我如何测试它吗?就像在触发之前打印东西一样。另外我的最后一个问题是,每当我的温度超过 24 度时,我想向 ESP32(闪烁 LED)发送配置更新。如何做到这一点?提前致谢
  • 触发前打印是什么意思?在哪里打印?恐怕我对ESP32 或 LED 一无所知。
  • 在 Google Cloud Shell 中仅打印温度 > 24 的数据!感谢您尽最大努力帮助我
猜你喜欢
  • 2018-12-01
  • 2020-05-18
  • 2021-01-25
  • 2022-09-27
  • 2017-11-14
  • 2019-05-12
  • 1970-01-01
  • 2020-09-24
  • 2021-10-05
相关资源
最近更新 更多