How to run synchronized third-party libraries gracefully without blocking

from sanic import Sanic
from sanic.response import text
import asyncio
import time
import threading

app = Sanic("MyHelloWorldApp")

print(threading.get_ident(), threading.get_native_id())


@app.get("/sync")
async def hello_world(request):
    print('start sync', threading.get_ident(), threading.get_native_id())
    time.sleep(10)  # third-party libraries
    return text("Hello, world.")


@app.get("/async")
async def hello_world2(request):
    await asyncio.sleep(10)
    return text("Hello, world.")

I know that there are methods like asyncio.to_thread(blocking_io), but is this the best practice? I see that if it is not async func in fastapi, it will automatically execute in the thread pool.

What’s your use case? Almost every time someone asks this question it is a sign that better dev patterns exist. Rarely would I recommend to someone to mix async and threads. Of course, at its core, your app is no different than any other async Python program and this is achievable even if not advisable.

For example, there is a third-party library that is written using requests. We need to use it in some businesses, and this part is difficult to rewrite as asynchronous. Most of our http apis are asynchronous

retval = await request.app.loop.run_in_executor(None, some_slow_io_function)