python - 如何处理错误或再次尝试使用 python 发布到 pubsub 消息谷歌
问题描述
我使用此脚本向 pubsub 中的主题发送消息:
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path("my-project", "my-topic")
while True:
msg = b"some message"
future = publisher.publish(topic_path, msg)
try:
result = future.result()
except Exception as ex:
# handle exception
print(ex)
time.sleep(3)
我的问题是当消息未在 pubsub 上发布时如何让我print(ex)
打印或检测消息何时未发送并尝试再次发布。
解决方案
您可以查看这篇文章,因为它为发布实现了错误处理。为获取回调创建了一个方法。它接受未来的对象和数据字符串。如果有异常,它将调用 exception() 以返回引发的异常。
def get_callback(f, data):
def callback(f):
try:
print(f.result())
futures.pop(data)
except: # noqa
print("Please handle {} for {}.".format(f.exception(), data))
return callback
该方法用于通过传递“future”和“data”参数来实现get_callback。其中future是一个对象,data是字符串。
for i in range(10):
data = str(i)
futures.update({data: None})
# When you publish a message, the client returns a future.
future = publisher.publish(topic_path, data.encode("utf-8"))
futures[data] = future
# Publish failures shall be handled in the callback function.
future.add_done_callback(get_callback(future, data))
# Wait for all the publish futures to resolve before exiting.
while futures:
time.sleep(5)
推荐阅读
- mysql - secure-file-priv 阻止我将 .CSV 导入数据库
- c - _Generic 代码块中的“')' 标记之前的预期说明符限定符列表”错误
- html - 前置标签在移动设备中没有响应
- python - 打开文件读取行打破字符串并以不同的顺序写入文件 PYTHON
- javascript - 如何在我的 HTML 项目中使用 JavaScript?
- laravel - Laravel Eloquent,在相关模型中将自定义列确定为外键
- python - Plotly条形图-根据正/负值更改颜色-python
- aws-lambda - AWS SAM 模板的本地工作流程是什么,它在 zip 文件中包含具有 python 依赖项的层
- javascript - 点击动画字体真棒图标从一个到另一个
- python - 进程间通信 Unity3d python