If I have an async view in Django, can I have it await a callback?
Pseudocode:
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
I would like to avoid having to implement the second part of my_view
inside callback
, but rather have an async function that returns the result in the original view as soon as the callback is executed.
I solved it using redis.
The view my_view
polls a redis pubsub queue:
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)
And the callback
view publishes in the queue:
def callback(request, result):
redis.publish("some_channel", result)