python-3.x - Azure python sdk 服务总线接收消息
问题描述
我对 azure python servicebus 有点困惑。
我有一个监听特定消息的服务总线 TOPIC 和 SUBSCRIPTION,我有接收这些消息的代码,然后它们将由 aws comprehend 处理。
按照 Microsoft 文档,接收消息的基本代码可以工作并且我可以打印它,但是当我将相同的逻辑与理解集成时它会失败。
这是示例,这是 Microsoft 文档中的一段代码:
with servicebus_client:
# get the Queue Receiver object for the queue
receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5)
with receiver:
for msg in receiver:
print("Received: " + str(msg))
# complete the message so that the message is removed from the queue
receiver.complete_message(msg)
输出是这个
{"ModuleId":"123458", "Text":"This is amazing."}
Receive is done.
我的第一个想法是收到的消息是一个 Json 对象。所以我开始编写代码以从 json 输出中读取数据,如下所示:
servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR)
with servicebus_client:
receiver = servicebus_client.get_subscription_receiver(
topic_name=TOPIC_NAME,
subscription_name=SUBSCRIPTION_NAME
)
with receiver:
received_msgs = receiver.receive_messages(max_message_count=10, max_wait_time=5)
for msg in received_msgs:
# print(str(msg))
message = json.dumps(msg)
text = message['Text']
#passing the text to comprehend
result_json= json.dumps(comprehend.detect_sentiment(Text=text, LanguageCode='en'), sort_keys=True, indent=4)
result = json.loads(result_json) # converting json to python dictionary
#extracting the sentiment value
sentiment = result["Sentiment"]
#extracting the sentiment score
if sentiment == "POSITIVE":
value = round(result["SentimentScore"]["Positive"] * 100,2)
elif sentiment == "NEGATIVE":
value = round(result["SentimentScore"]["Negative"] * 100,2)
elif sentiment == "NEUTRAL":
value = round(result["SentimentScore"]["Neutral"] * 100,2)
elif sentiment == "MIXED":
value = round(result["SentimentScore"]["Mixed"] * 100,2)
#store the text, sentiment and value in a dictionary and convert it tp JSON
output={'Text':text,'Sentiment':sentiment, 'Value':value}
output_json = json.dumps(output)
print('Text: ',text,'\nSentiment: ',sentiment,'\nValue: ', value)
print('In JSON format\n',output_json)
receiver.complete_message(msg)
print("Receive is done.")
但是当我运行它时,我收到以下错误:
TypeError: Object of type ServiceBusReceivedMessage is not JSON serializable
有没有人可以帮助我了解从接收返回的服务总线类型是什么?
谢谢大家!谢谢
解决方案
有没有人可以帮助我了解从接收返回的服务总线类型是什么?
接收到的消息的类型ServiceBusReceivedMessage
是从 派生的ServiceBusMessage
。可以从其body
属性中获取消息的内容。
你能试试这样的吗:
message = json.dumps(msg.body)
推荐阅读
- r - 如果我只知道数据框的字符串变量名称,如何更改列的值?
- asp.net-core - 向使用“身份作为 UI”的 Web 应用程序验证 .NET Core 2.1 SignalR 控制台客户端
- javascript - preventDefault 在锚标记单击时停止刷新
- typescript - 打字稿错误 - 预期 1 个参数,但得到 0
- java - ANDROID STUDIO 中的文件夹视图
- javascript - ActiveAdmin 破坏了 Rails JQuery UJS。不显眼的 JavaScript ajax:success 和 ajax:error 没有触发或被调用
- node.js - 时刻无效日期 - 字符串到时刻 - hh:mm:ss zzz mm/dd/yyyy (02:10:02 SGT 06/07/2018)
- dns - DNS 查找得到不存在的域错误
- javascript - HTML 未正确处理
- excel - 将工作表中的所有行获取到另一个工作表中,其中每行包含一个与某个值匹配的单元格