【问题标题】:How can I publish a message in Redis channel asynchronously with python?如何使用 python 在 Redis 通道中异步发布消息?
【发布时间】:2020-12-13 20:28:48
【问题描述】:

在我现有的 djangorest api 中,我想从 python 代码一侧在 Redis 通道中发布消息。我想异步执行此操作,即想调用一个异步函数,该函数将向通道发送消息,同时我的 api 应该响应用户而不是阻止该 redis 通信。

让我们看看例子。

以下代码运行良好

#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
    )


但我不想等待 redis 连接并发布消息,而是希望像下面这样异步执行它


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
    )


【问题讨论】:

    标签: python django-rest-framework redis python-asyncio


    【解决方案1】:

    您不能等待连接和 redis,因为它们不是协程。它看起来像:

     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')
    

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2016-06-26
      • 2018-03-30
      • 1970-01-01
      • 2022-06-24
      • 2021-10-20
      • 1970-01-01
      • 2021-12-05
      • 2017-09-26
      相关资源
      最近更新 更多