Skip to content

Instantly share code, notes, and snippets.

@almoorthi
Forked from lukin0110/blocking_api.py
Created March 14, 2023 10:26
Show Gist options
  • Save almoorthi/2dbf7db365807f3b3afcdb78edc5b225 to your computer and use it in GitHub Desktop.
Save almoorthi/2dbf7db365807f3b3afcdb78edc5b225 to your computer and use it in GitHub Desktop.
"""
Non blocking example:
1. Browse to `localhost:8000/sleep1`
2. Browse to `localhost:8000/`
You'll observe that the first call will take 5 seconds and the second call will be executed immediately.
Blocking example:
1. Browse to `localhost:8000/sleep2`
2. Browse to `localhost:8000/`
You'll observe that the seconds call will be blocked by the first call. After the first call is executed it will execute
the second.
"""
import uvicorn
import time
from fastapi import FastAPI
from starlette.concurrency import run_in_threadpool as pool
app = FastAPI()
@app.get("/")
def read_root():
# This will go the 'Event loop'
# The event loop decides to execute it in a threadpool
return {"Hello": "World"}
@app.get("/sleep1")
def sleep1():
# This will go the 'Event loop'
# The event loop decides to execute it in a threadpool
time.sleep(5)
return {}
@app.get("/sleep2")
async def sleep2():
# This will be executed in the 'Event loop'
# This will block the entire 'Event loop' since time.sleep() is a synchronous method
time.sleep(5)
return {}
@app.get("/sleep3")
async def sleep3():
print("A")
await pool(time.sleep, 5)
print("B")
return {}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment