Skip to content

Instantly share code, notes, and snippets.

@lukin0110
Last active March 19, 2024 14:24
Show Gist options
  • Save lukin0110/0074ec5325224674010193bb95f8b835 to your computer and use it in GitHub Desktop.
Save lukin0110/0074ec5325224674010193bb95f8b835 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 second 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 to the 'Event loop'
# The event loop decides to execute it in a threadpool
return {"Hello": "World"}
@app.get("/sleep1")
def sleep1():
# This will go to 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