calling a function asynchronously

Kirill Ratkin kirill.ratkin at devoteam.com
Wed Mar 30 12:27:54 EDT 2022


Hi,

You can use asyncio.create_task and gather results. See docs -
https://docs.python.org/3/library/asyncio-task.html

But think twice what you want to do in async task. Do you use synchronous
requests to database? If yes it will blocks eventloop...

If you use Django it makes sense to use something like
'django-background-tasks'

It just saves your time possibly.

// BR

ср, 30 мар. 2022 г., 19:14 Larry Martell <larry.martell at gmail.com>:

> I have a django app, and for a certain request I need to kick off a
> long running task. I want to do this asynchronously and immediately
> return a response. I tried using subprocess.Process() but the forked
> process does not have a django database connection. I then tried
> posting a request using ajax but that does not have a django session
> so it's not authorized. Tried using asyncio but I am finding the
> caller of the async function does not return until the async function
> returns - maybe I am doing something wrong, as it does appear to be
> actually asynchronous. I tried this test:
>
> import asyncio
> import time
>
> async def long():
>     for i in range(100):
>        time.sleep(10)
>
> asyncio.run(long())
> print('after asyncio.run')
>
> The final print does not come out until after long() completes.
>
> Is there any way to do this?
> --
> https://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list