Shamim
Shamim

Reputation: 705

How can I publish a message in Redis channel asynchronously with python?

In my existing djangorest api I want to publish a message in a Redis channel from side the python code. I want to do it asynchronously i.e, want to call an async function which will send a message to the channel and at the same time my api should response the user instead blocking at that redis communication.

Lets see example.

Below code is working well

#Python function (api function)
def create(self, request, *args, **kwargs):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    #some business logic
    connection = redis.Redis(host=config("REDIS_SERVER_URL"), port=config("REDIS_SERVER_PORT"), db=config("REDIS_SERVER_DB"))
    connection.publish('my_channel', 'my pubsub message')
    
    return Response(      
        data={
            'status': True,
            'message': "Order Successfully Created",
            'data': response
        },
        status=status.HTTP_201_CREATED
    )


But I don't want to wait for redis connection and publishing the message rather want to do it asynchronously like below


async def publish_message(channel, message):
    connection = await redis.Redis(host=config("REDIS_SERVER_URL"), port=config("REDIS_SERVER_PORT"), db=config("REDIS_SERVER_DB"))
    await connection.publish('channel', 'my pubsub message')
    return "Nice"



#Python function (api function)
def create(self, request, *args, **kwargs):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    #some business logic
    publish_message('my_channel', 'my pubsub message')
    
    return Response(      
        data={
            'status': True,
            'message': "Order Successfully Created",
            'data': response
        },
        status=status.HTTP_201_CREATED
    )


Upvotes: 0

Views: 1008

Answers (1)

V-outsider
V-outsider

Reputation: 11

You can't await connection and redis, because they're not corutines. It will looks like:

 async def publish_message(channel, message):
        connection = redis.Redis(host=config("REDIS_SERVER_URL"), port=config("REDIS_SERVER_PORT"), db=config("REDIS_SERVER_DB"))
        connection.publish('channel', 'my pubsub message')
        return "Nice"

def it_works():
    await publish_message('gg', 'wp')

Upvotes: 1

Related Questions