如何使用 Python3 和 CURL 中的 HTTP 桥发布到 GCP pub/sub 主题?

How to publish to a GCP pub/sub topic using HTTP Bridge in Python3 & CURL?

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

**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

我还尝试使用

中描述的 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 发布上面描述的 'payload',为什么会是正确的格式?

您似乎正在使用 JSON 负载,其中 data 字段设置为对象,而不是二进制 string。尝试 json.dumps 'data' 字段中的对象或将 'data' 字段作为字符串发送。

来自这份文件。 https://cloud.google.com/iot/docs/reference/cloudiotdevice/rest/v1/projects.locations.registries.devices/publishEvent

我发现我的负载请求正文不正确。

所以负载应该如下所示..

s= json.jumps('json object')
payload = {"subFolder": 'Sub_FOLDER_NAME', "binaryData": base64.b64encode(s.encode('utf-8'))}