首页 > 解决方案 > 如何在 Python3 和 CURL 中使用 HTTP 桥发布到 GCP 发布/订阅主题?

问题描述

我正在尝试使用 python3 和 CURL 通过 HTTP 桥发布到发布/订阅主题。

**Python3**

import json
import logging
import os
import socket
import sys
import time
import requests
URL = 'https://cloudiotdevice.googleapis.com/v1/projects/{}/locations/{}/registries/{}/devices/{}:publishEvent'
JWT = 'JWT'

def main():
    if not URL or not JWT:
        sys.exit("Are the Environment Variables set?")
    get_sensor_data(socket.gethostname())
def get_sensor_data(device_id):
    while True:
        print("in get_sensor data")
        payload = {'device': str('asd'),
                   'type': str('adssaff'),
                   'timestamp': str(time.time()),
                   'data': json.dumps({'temperature': str('23'),
                            'humidity': str('442')})}
        post_data(payload)
        print("data printed")
        time.sleep(5)
def post_data(payload):
    payload = json.dumps(payload)
    headers = {
        'Content-Type': 'application/json; charset=utf-8',
        'Authorization': JWT
    }
    try:
        req = requests.post(URL, json=str(payload), headers=headers)
        print("request Successfull "+str(req))
    except requests.exceptions.ConnectionError:
        logging.error('Error posting data to Cloud Function!')
    except requests.exceptions.MissingSchema:
        logging.error('Error posting data to Cloud Function! Are Environment Variables set?')
if __name__ == '__main__':

这给出了错误 400,因为我认为我没有描述子文件夹。现在我很困惑,我在哪里可以在我的代码中定义子文件夹(主题名称)?并且只缺少子文件夹吗?或者我也做错了什么?

卷曲

我还尝试使用中描述的 CURL 命令

https://cloud.google.com/iot/docs/how-tos/http-bridge

命令是

curl -X POST -H 'authorization: Bearer JWT' -H 'content-type: application/json' --data '{"binary_data": "DATA", "sub_folder": "SUBFOLDER"}' -H 'cache-control: no-cache' 'https://cloudiotdevice.googleapis.com/v1/projects/{project-id}/locations/{cloud-region}/registries/{registry-id}/devices/{device-id}:publishEvent'

它触发了我的云功能,这意味着授权有效,但我无法在我的日志中看到“DATA”。我假设我没有为 binary_data 提供正确的格式。如果我也想使用 curl 发布上述“有效负载”,为什么会是正确的格式?

标签: google-cloud-platformgoogle-cloud-functionsgoogle-cloud-pubsubgoogle-cloud-iot

解决方案


看起来您正在使用将data字段设置为对象的 JSON 有效负载,而不是 binary string。尝试将字段中json.dumps的对象'data'或将'data'字段作为字符串发送。


推荐阅读