I am using FastAPI, and strangely, only on the first API call I get the error "RuntimeError: Cannot enter into task while another task is being executed." I have supplied some sample code that should reproduce this error.

import asyncio
import nest_asyncio
from fastapi import FastAPI
import nest_asyncio
nest_asyncio.apply()

app = FastAPI(title="Test Api")

async def task1():
    print("task1 before")
    await asyncio.sleep(0.4)
    print("task1 after")


async def task2():
    print("task2 before")
    await asyncio.sleep(0.4)
    print("task2 after")

@app.get("/test")
async def test():
    async def main():
        print("main: start")
        task = asyncio.create_task(task1())
        asyncio.run(task2())
        print("main: end")
        await task

    asyncio.run(main())

I am using the command uvicorn main:app to run the API on localhost. Strangely, despite getting this error, the code always seems to execute properly.

1

There are 1 best solutions below

3
On

Running on Python 3.10 and FastAPI 0.79 and Uvicorn 0.18.2, it's only possible to patch a asyncio loop. I have the above code working by running uvicorn "main:app" --loop asyncio