google-cloud-platform - 如何在 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 发布上述“有效负载”,为什么会是正确的格式?
解决方案
看起来您正在使用将data
字段设置为对象的 JSON 有效负载,而不是 binary string
。尝试将字段中json.dumps
的对象'data'
或将'data'
字段作为字符串发送。
推荐阅读
- c++ - 从 unordered_set 中获取给定大小 k 的所有子集?
- php - 如何使用 localhost 将数据发送到数据库
- cloud - ovh 专用服务器上的 1 gbps 包括带宽的限制?
- java - 从 ElasticSearch 7.3 中获取字段。用 Springboot java 编写文档
- php - 使用 Laravel Nova Indicator Field 使文本和自定义字段可排序?
- bash - 尝试递增关联数组元素时出现错误的数组下标错误
- azure - 最具成本效益的云托管数据库和应用服务?
- pagespeed - Pagespeed 分数与 gtmetrix 不同 - 关于 pagespeed 分数的问题也不同
- c++ - 是否可以将c ++ 20中的结构分解为模板参数列表
- c# - 使用循环编写这个 3+3 数学问题的更好方法是什么?