Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

python 3.x - How to read header key:value pair when subscribing a message with Paho MQTT

I am adding a header key:value pair when publishing a message to my rabbitmq broker using pika like

channel.basic_publish(exchange=self.exchange,
                      routing_key=self.routing_key,
                      properties=pika.BasicProperties(
                          headers={'key': 'value'} 
                      ),
                      body=message)

On my client side I am subscribing the topic with Paho MQTT using websockets. How can I retrieve the same messages header using Paho MQTT . I have tried the following methods which doesn't work for me

def onMessage(client, userdata, message):

    print("topic: " + message.topic + ", message: " + str(message.payload, 'utf-8'))
    print(client.headers)
    print(userdata.headers)
    print(message.headers)

UPDATE

I have found that message has an Attribute 'properties'. But when I tried to print(message.properties) it is giving AttributeError: properties


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Pika is a AMQP client publishing messages in AMQP format.

Paho is a MQTT client and as such can only handle messages in that format. At MQTT v3 (the Paho Python client does not support MQTT v5 yet) the protocol does not have any scope to hold message attributes. The only properties a MQTT v3 message has are topic, payload, QOS and a retained bit.

So the RabbitMQ broker must be doing a format conversion and stripping the attributes off before moving the message from the Queue to the MQTT Topic.

So basically I'm saying there are no attributes in the MQTT message to read.

EDIT: It looks like the latest version of the Paho Python client does support MQTTv5 (the doc has just not been updated). While MQTTv5v does support Key/Value pair attributes in the header, it will depend on the client actually connecting using MQTTv5 and RabbitMQ supporting both MQTTv5 and copying the values over to the new format.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...