I'm creating an async function to upload a video. The goal is to run the video upload asynchronously in the background without making the user wait. The user will be redirected to another page while the video is uploading.
Following instructions in Python's asyncio docs, I'm using create_task() as that seems to be the simplest solution.
In the following code, it works but it is not running asynchronously. HttpResponseRedirect is not running until after the video is fully uploaded.
I also inserted 2 lines to check whether upload_video() is running asynchronously and it is. print('before') and print('after') are both printed to the console before the upload_video function completes. However, the final HttpResponseRedirect() does not run until all the code has been executed.
async def my_async_func(request):
if request.method == 'POST':
video = request.FILES['video']
print('before')
asyncio.create_task(upload_video(video))
print('after')
return HttpResponseRedirect(... somewhere)
async def upload_video(video):
...
Basically despite all the async syntax & logic I wrote, the function is still running like a typical synchronous django view function.
Why is this? What do I need to change to make upload_video() run asynchronously and return HttpResponseRedirect() without waiting?
P.S. I also tried replacing create_task() with ensure_future() but it gave me the same result - the videos uploads but not asynchronously.