close

How to call a async function from a synchronized code Python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to call a async function from a synchronized code Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to call a async function from a synchronized code Python?

  1. How to call a async function from a synchronized code Python?

    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.

  2. call a async function from a synchronized code Python

    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.

Method 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).

Method 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:

def work(p):
    # intensive work being done in the background


def endpoint():
    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.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read