如何在Python中将异步函数与回调结合起来?

问题描述 投票:0回答:1

如果我在 Django 中有一个异步视图,我可以让它等待回调吗?

伪代码:

async def my_view(request):
    # Use external services that eventually send data to /callback/
    do_something()
    # Wait for the callback
    result = await callback_executed()
    do_something_else(result)

# view for /callback/
def callback(request, result):
    # Here control should be returned to my_view providing the result data

我想避免在

my_view
中实现
callback
的第二部分,而是有一个异步函数,一旦执行回调,它就会在原始视图中返回结果。

python django django-rest-framework async-await callback
1个回答
0
投票

我用redis解决了。

视图

my_view
轮询redis pubsub队列:

def my_view(request)
    pubsub = redis.pubsub()
    await pubsub.subscribe("some_channel")
    # Use external services that eventually send data to /callback/
    do_something()
    # Wait for the callback
    for _ in range(30):
        message = await pubsub.get_message(ignore_subscribe_messages=True)
        if message:
            result = message["data"]
            do_something_else(result)
            break
        await asyncio.sleep(1.0)

并且

callback
视图在队列中发布:

def callback(request, result):
    redis.publish("some_channel", result)
© www.soinside.com 2019 - 2024. All rights reserved.