Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI not behaving asynchronously

I'm probably not understanding the asynchronous concept correctly in FastAPI.

I'm accessing the root endpoint of the following app from two clients at the same time. I'd expect FastAPI to print Started twice in a row at the start of the execution:

from fastapi import FastAPI
import asyncio

app = FastAPI()

@app.get("/")
async def read_root():
    print('Started')
    await asyncio.sleep(5)
    print('Finished')
    return {"Hello": "World"}

Instead I get the following, which looks very much non asynchronous:

Started
Finished
INFO: ('127.0.0.1', 49655) - "GET / HTTP/1.1" 200
Started
Finished
INFO: ('127.0.0.1', 49655) - "GET / HTTP/1.1" 200

What am I missing?

like image 212
Florentin Hennecker Avatar asked Oct 14 '19 15:10

Florentin Hennecker


People also ask

Is FastAPI synchronous or asynchronous?

Unlike Flask, FastAPI is implemented on ASGI and allows you to create both asynchronous and synchronous applications natively.

Is FastAPI single threaded?

Amazing single-threaded performance with FastAPI — optimize your code for a HUGE performance boost! Python has many web frameworks the most popular being Django and Flask.

How many requests can FastAPI handle?

FastAPI (Async) - Python FastAPI in asynchronous mode clocks in at ~228 requests per second.

Is FastAPI production ready?

Not only is FastAPI intuitive and straight-forward to use in projects, but the FastAPI code also has 100% test coverage hence it's production-ready robust code.


Video Answer


2 Answers

How do you ensure there are multiple simultaneous requests?

Your code is fine - try using following command for testing:

for n in {1..5}; do curl http://localhost:8000/ & ; done

Your browser might be caching subsequent requests to the same URL.

like image 64
Paweł Żukowski Avatar answered Sep 21 '22 21:09

Paweł Żukowski


Well from what the demos in this github issue show, it's probably not due to FastAPI but the client that runs the requests.

like image 32
Florentin Hennecker Avatar answered Sep 24 '22 21:09

Florentin Hennecker