Change Virtual Host of RabbitMQ at runtime for Django/Celery

Today I needed to route tasks to a virtual host on RabbitMQ from a regular Django app with the aid of Celery.

To achieve this, you need to access the settings dictionary like so:

from django.conf import settings

Let’s view the full list of what it contains.

dir(settings)

You will now see the key BROKER_URL. This is what you need to change.

Set this to some other URL that contains the virtual host that you want to route your task to just before you call the task.

settings.BROKER_URL = 'amqp://admin:admin@192.168.2.109:5672/vhost'
# make call to task
# my_task.send_email.delay()
# reset settings.BROKER_URL

vhost represents the virtual host you want to send the task to.

Kindly note that changing this URL at runtime is not encouraged and do remember to reset the settings.BROKER_URL back to what it was before you called the task

I hope this info helped.