Monday, 4 October 2021

How long does the event_loop live in a Django>=3.1 async view

I am playing around with the new async views from Django 3.1.

Some benefits I would love to have is to do some simple fire-and-forget "tasks" after the view already gave its HttpResponse, like sending a push notification or sending an email. I am not looking for solutions with third-party packages like celery!

To test this async views I used some code from this tutorial: https://testdriven.io/blog/django-async-views/

async def http_call_async():
    for num in range(1, 200):
        await asyncio.sleep(1)
        print(num)
        
    # TODO: send email async
    print('done')


async def async_view(request):
    loop = asyncio.get_event_loop()
    loop.create_task(http_call_async())
    return HttpResponse("Non-blocking HTTP request")

I started the django server with uvicorn.

When I make a request to this view it will immediately return the HTTP-response "Non-blocking HTTP request".

In the meantime and after the HTTP-response, the event loop continues happily to print the numbers up to 200 and then print "done".

This is exactly the behaviour I want to utilize for my fire-and-forget tasks.

Unfortunatly I could not find any information about the lifetime of the event loop running this code.

How long does the event loop live? Is there a timeout? On what does it depend? On uvicorn? Is that configurable?

Are there any resources which discuss this topic?



from How long does the event_loop live in a Django>=3.1 async view

No comments:

Post a Comment