-
Install dependencies:
pip install fastapi uvicorn
-
Start the FastAPI server:
uvicorn your_filename:app --reload
-
Visit the following URLs to test:
/blocking: Waits for 5 seconds due to blocking I/O./non-blocking: Also waits for 5 seconds, but it's non-blocking and won't prevent the server from handling other requests./compare: Runs two async I/O operations concurrently and returns after both complete./benchmark: Demonstrates handling multiple concurrent requests efficiently.
-
Blocking I/O Example:
- The
/blockingendpoint uses a traditional synchronousdeffunction withtime.sleep(), which blocks the thread for 5 seconds. - This blocks the entire server, meaning no other requests will be processed during the sleep.
- The
-
Non-Blocking I/O Example:
- The
/non-blockingendpoint usesasync defandasyncio.sleep(), which does not block the thread. - Other requests can be processed while this operation is waiting.
- The
-
Compare Endpoint:
- We use
asyncio.gather()to run twonon-blocking_iooperations concurrently. - This shows how FastAPI handles concurrent operations within a single request.
- We use
-
Benchmark Endpoint:
- The
/benchmarkendpoint simulates handling 10 concurrent requests by creating 10 non-blocking tasks and running them simultaneously.
- The