![](/img/trans.png)
[英]How to modify ack deadline for a push subscription message on GCP Pub/Sub?
[英]GCP Pub/Sub & Python - How To Acquire JSON Keys From Message?
我必须首先道歉,因为我刚刚开始使用 Pub/Sub,所以我可能缺乏对 GCP 功能的理解。
我正在尝试调整 Google 自己的 Python 脚本,以从 Cloud Run 中的 Pub/Sub 接收消息( https://cloud.google.com/run/docs/triggering/pubsub-push#run_pubsub_handler-python ):
@app.route("/", methods=["POST"])
def index():
envelope = request.get_json()
if not envelope:
msg = "no Pub/Sub message received"
print(f"error: {msg}")
return f"Bad Request: {msg}", 400
if not isinstance(envelope, dict) or "message" not in envelope:
msg = "invalid Pub/Sub message format"
print(f"error: {msg}")
return f"Bad Request: {msg}", 400
pubsub_message = envelope["message"]
name = "World"
if isinstance(pubsub_message, dict) and "data" in pubsub_message:
name = base64.b64decode(pubsub_message["data"]).decode("utf-8").strip()
print(f"Hello {name}!")
return ("", 204)
现在我使用的 Pub/Sub 主题有一个 AVRO 模式,例如:
{
"type": "record",
"name": "Avro",
"fields": [
{
"name": "ext_file_id",
"type": "string"
},
{
"name": "input_bucket",
"type": "string"
}
]
}
我需要在 Cloud Run(我的 Python 脚本)中做的是获取 JSON 主体键(ext_file_id 和 input_bucket)及其值。
考虑到我通过以下方式获得 JSON:
envelope = request.get_json()
会不会是这样的:
envlope.body.ext_file_id
envelope.body.input_bucket
或者是其他东西?
我尝试了以下方法无济于事:
envelope["ext_file_id"]
envelope["input_bucket"]
当您从 PubSub 收到 JSON 时,您会收到包含此格式的message
字段的 JSON
{
"data": string,
"attributes": {
string: string,
...
},
"messageId": string,
"publishTime": string,
"orderingKey": string
}
您的消息在data
字段中的 base64 中编码,在您的代码中
pubsub_message["data"]).decode("utf-8")
然后你必须 JSON 解析( json.loads(data)
)这个内容,然后得到你想要的字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.