Dependencies in Python
Depends injects shared setup, and the framework caches it per request.
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
def get_db():
db = {"rows": ["python", "rust"]}
try:
yield db
finally:
db["closed"] = True
def pagination(limit: int = 10, offset: int = 0):
return {"limit": min(limit, 50), "offset": offset}
@app.get("/langs")
def langs(db=Depends(get_db), page=Depends(pagination)):
rows = db["rows"][page["offset"]:page["offset"] + page["limit"]]
return {"rows": rows, "page": page}
client = TestClient(app)
print(client.get("/langs", params={"limit": 1}).json())
app.dependency_overrides[get_db] = lambda: {"rows": ["fake"]}
print(client.get("/langs").json()["rows"])
How it works
- A dependency is just a callable with its own parameters.
- It can yield, which gives it teardown.
- Overriding one is how tests replace a database.
Keywords and builtins used here
deffinallyget_dbintlambdalangsminpaginationprintreturntryyield
The run, in numbers
- Lines
- 29
- Characters to type
- 659
- Tokens
- 229
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 125 seconds.
Step 1 of 3 in Dependencies & async, step 10 of 19 in Web services & data access.