import pika
from decouple import config
from django.conf import settings
class CloudAMQPConsumerMixin:
url = settings.CLOUD_AMQP_URL
def __init__(self, queue: str) -> None:
self.queue = queue
self._connect()
def _connect(self):
params = pika.URLParameters(self.url)
params.heartbeat = 10
params.blocked_connection_timeout = 5
self.connection = pika.BlockingConnection(params)
def send_message(self, text):
self.channel = self.connection.channel() # start a channel
self.channel.queue_declare(queue=self.queue)
self.channel.basic_publish(exchange="", routing_key=self.queue, body=text)
print(f" [x] Sent {text}")
ampq_publisher = CloudAMQPConsumerMixin(queue="notification")
In my endpoint:
def list(self, request, *args, **kwargs):
import json
from libraries.queue.rabbitmq import ampq_publisher
print("Send a message to the queue!")
notification_message = {}
notification_message["user"] = str(request.user)
notification_message["profile"] = str(request.user.profile)
ampq_publisher.send_message(json.dumps(notification_message))
return Response(status=status.HTTP_200_OK)
I could not find how to format, let me know if there is.
Thank you for your help!