Call Async Function From Sync Function, While The Synchronous Function Continues : Python
Solution 1:
asyncio
can't run arbitrary code "in background" without using threads. As user4815162342 noted is asyncio
you run event loop that blocks main thread and manages execution of coroutines.
If you want to use asyncio
and take advantage of using it, you should rewrite all your functions that uses coroutines to be coroutines either up to main function - entry point of your program. This main coroutine is usually passed to run_until_complete
. This little post reveals this topic in more detail.
Since you're interested in Flask, take a look Quart: it's a web framework that tries to implement Flask API (as much as it's possible) in terms of asyncio
. Reason this project exists is because pure Flask isn't compatible with asyncio
. Quart is written to be compatible.
If you want to stay with pure Flask, but have asynchronous stuff, take a look at gevent. Through monkey-patching it can make your code asynchronous. Although this solution has its own problems (which why asyncio
was created).
Solution 2:
Maybe it's a bit late, but I'm running into a similar situation and I solved it in Flask by using run_in_executor:
defwork(p):
# intensive work being done in the backgrounddefendpoint():
p = ""
loop = asyncio.get_event_loop()
loop.run_in_executor(None, work, p)
I'm not sure however how safe this is since the loop is not being closed.
Solution 3:
Assuming the synchronous function is inside an asynchronous function, you can solve it using exceptions. Pseudo code:
classCustomError(Exception):
passasyncdefmain():
deftest_syn():
time.sleep(2)
# Start Asyncraise CustomError
try:
test_syn()
except CustomError:
await asyncio.sleep(2)
Post a Comment for "Call Async Function From Sync Function, While The Synchronous Function Continues : Python"