Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rabbitmq listener using pika in django

I have a django application and I want to consume messages from a rabbit mq. I want the listener to start consuming when I start the django server.I am using pika library to connect to rabbitmq.Proving some code example will really help.

like image 532
Souradipta Roy Avatar asked Jun 01 '18 10:06

Souradipta Roy


1 Answers

First you need to somehow run your application at the start of the django project https://docs.djangoproject.com/en/2.0/ref/applications/#django.apps.AppConfig.ready

def ready(self):
    if not settings.IS_ACCEPTANCE_TESTING and not settings.IS_UNITTESTING:
        consumer = AMQPConsuming()
        consumer.daemon = True
        consumer.start()

Further in any convenient place

import threading

import pika
from django.conf import settings


class AMQPConsuming(threading.Thread):
    def callback(self, ch, method, properties, body):
        # do something
        pass

    @staticmethod
    def _get_connection():
        parameters = pika.URLParameters(settings.RABBIT_URL)
        return pika.BlockingConnection(parameters)

    def run(self):
        connection = self._get_connection()
        channel = connection.channel()

        channel.queue_declare(queue='task_queue6')
        print('Hello world! :)')

        channel.basic_qos(prefetch_count=1)
        channel.basic_consume(self.callback, queue='queue')

        channel.start_consuming()

This will help http://www.rabbitmq.com/tutorials/tutorial-six-python.html

like image 91
Alexander Astashov Avatar answered Sep 24 '22 11:09

Alexander Astashov