12

I am writing an automated test to test a consumer. So far I did not need to include a header when publishing messages but now I do. And it seems like its lacking documentation.

This is my publisher:

class RMQProducer(object):

    def __init__(self, host, exchange, routing_key):
        self.host = host
        self.exchange = exchange
        self.routing_key = routing_key

    def publish_message(self, message):
        connection = pika.BlockingConnection(pika.ConnectionParameters(self.host))
        channel = connection.channel()
        message = json.dumps(message)
        channel.basic_publish(exchange=self.exchange,
                              routing_key=self.routing_key,
                              body=message)

I want to do smtn like:

channel.basic_publish(exchange=self.exchange,
                      routing_key=self.routing_key,
                      body=message,
                      headers={"key": "value"})

Whats the correct way to add headers to this message?

raitisd
  • 3,875
  • 5
  • 26
  • 37
  • You can take a look at an example I have for pika here, on how to add headers. https://github.com/eandersson/python-rabbitmq-examples/blob/master/Flask-examples/pika_async_rpc_example.py#L113 – eandersson Jun 08 '16 at 09:37
  • You have another example with my own amqp library here as well https://github.com/eandersson/amqpstorm/blob/stable/examples/classic_publisher.py#L16 – eandersson Jun 08 '16 at 09:38

3 Answers3

24

You would use pika.BasicProperties to add headers.

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

The official documentation for pika does indeed not cover this scenario exactly, but the documentation does have the specifications listed. I would would strongly recommend that you bookmark this page, if you are going to continue using pika.

Al.G.
  • 4,327
  • 6
  • 31
  • 56
eandersson
  • 25,781
  • 8
  • 89
  • 110
3

cant say where i get this, but i do it like:

props = pika.BasicProperties({'headers': {'key': 'value'}})
channel.basic_publish(exchange=self.exchange,
                          routing_key=self.routing_key,
                          body=message, properties = props)
Matroskin
  • 429
  • 4
  • 5
1

The official document was mentioned as follows:

hdrs = {u'': u' ',
    u'': u'',
    u'': u''}
properties = pika.BasicProperties(app_id='example-publisher',
    content_type='application/json',  
    headers=hdrs)