1

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.

  • 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 Jul 28 '22 at 21:04
  • @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 Jul 28 '22 at 21:16

1 Answers1

0

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

JarroVGIT
  • 4,291
  • 1
  • 17
  • 29
  • I am still getting the same error. Just to clarify, I am actually having no problem getting the API to run, and even no problem making requests. It's just that, only the first time I make a request, I get the error; despite getting an error, the API still successfully returns the correct response. – bravesheeptribe Jul 28 '22 at 21:26
  • And have you moved the the import and the `apply()` function to the the top of your file, before any other import? – JarroVGIT Jul 28 '22 at 21:36
  • Yes, and it didn't help. – bravesheeptribe Jul 28 '22 at 23:42