0
votes

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
Running this code (python 3.10, FastAPI 0.79) produces a different error (RuntimeError: this event loop is already running.). I actually expected that error, not yours. Is there a reason you are using nest_asyncio? - JarroVGIT
@JarroVGIT Obviously the example I provided isn't exactly what my actual project looks like. For my actual project, since I'm using nested event loops, I need to use nest_asyncio. If it makes a difference, I am on Python 3.9.12. - bravesheeptribe

1 Answers

0
votes

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