0

我对 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

有没有人可以帮助我了解从接收返回的服务总线类型是什么?

谢谢大家!谢谢

4

1 回答 1

0

有没有人可以帮助我了解从接收返回的服务总线类型是什么?

接收到的消息的类型ServiceBusReceivedMessage是从 派生的ServiceBusMessage。可以从其body属性中获取消息的内容。

你能试试这样的吗:

message = json.dumps(msg.body)
于 2021-09-24T14:28:20.943 回答