๐ฌ ๐ โฎ๏ธ ๐¶
๐ ๐ โฎ๏ธ ๐ฌ¶
๐ค ๐ ๐โ ๐ ๐ช ๐ ๐ ๐ โฎ๏ธ ๐ฌ.
๐ ๐ซ ๐ โฎ๏ธ ๐ ๐ (๐ซ ๐ ๐ง-๐ โซ๏ธ ๐ช โ๏ธ).
โฉ๏ธ, ๐ ๐ ๐ ๐ ๐ ๐ ๐ โ๏ธ ๐ด โฎ๏ธ ๐ฏ (๐ฒ ๐ด ๐ฏ ๐ฏ), & ๐ ๐ ๐ฒ ๐ ๐ช โ๏ธ ๐โ ๐ฒ โฎ๏ธ ๐ โ๏ธ.
โ๏ธ ๐ผ: ๐ข ๐โ๐ฆบ¶
๐ผ ๐ช ๐ ๐ โ๏ธ ๐ข ๐ค ๐โ๐ฆบ ๐ ๐ ๐ช ๐ค.
๐ ๐จ โซ๏ธ ๐ค & โซ๏ธ ๐จ ๐ ๐ฉโ๐ป.
๐ ๐โ๐ฆบ 5๏ธโฃ๐ ๐ ๐ ๐ ๐จ, & ๐ค โซ๏ธ ๐ช โ โ ๐ฐ ๐ ๐ฅ ๐ โ๏ธ ๐ง ๐ ๐ฉโ๐ป ๐ฏ.
๐ ๐ฒ ๐ ๐ฏ ๐ข ๐โ๐ฆบ ๐, โ๏ธ ๐ซ ๐ฏ ๐ค โซ๏ธ ๐ ๐ฏ ๐ ๐.
๐ ๐ผ, ๐ ๐ช ๐ ๐ ๐ ๐ค ๐ ๐โ๐ฆบ, & โ๏ธ ๐ ๐ ๐ ๐จ ๐ ๐ฉโ๐ป, ๐ด ๐ ๐ฏ.
โ๏ธ app.dependency_overrides
๐ข¶
๐ซ ๐ผ, ๐ FastAPI ๐ธ โ๏ธ ๐ข app.dependency_overrides
, โซ๏ธ ๐
dict
.
๐ ๐ ๐ฌ, ๐ ๐ฎ ๐ โฎ๏ธ ๐ (๐ข), & ๐ฒ, ๐ ๐ ๐ (โ1๏ธโฃ ๐ข).
& โคด๏ธ FastAPI ๐ ๐ค ๐ ๐ โฉ๏ธ โฎ๏ธ ๐.
from typing import Union
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
async def common_parameters(
q: Union[str, None] = None, skip: int = 0, limit: int = 100
):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return {"message": "Hello Items!", "params": commons}
@app.get("/users/")
async def read_users(commons: dict = Depends(common_parameters)):
return {"message": "Hello Users!", "params": commons}
client = TestClient(app)
async def override_dependency(q: Union[str, None] = None):
return {"q": q, "skip": 5, "limit": 10}
app.dependency_overrides[common_parameters] = override_dependency
def test_override_in_items():
response = client.get("/items/")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": None, "skip": 5, "limit": 10},
}
def test_override_in_items_with_q():
response = client.get("/items/?q=foo")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
def test_override_in_items_with_params():
response = client.get("/items/?q=foo&skip=100&limit=200")
assert response.status_code == 200
assert response.json() == {
"message": "Hello Items!",
"params": {"q": "foo", "skip": 5, "limit": 10},
}
Tip
๐ ๐ช โ ๐ ๐ ๐ โ๏ธ ๐ ๐ FastAPI ๐ธ.
โฎ๏ธ ๐ ๐ช โ๏ธ โก ๐ ๏ธ ๐ข, โก ๐ ๏ธ ๐จโ๐จ (๐โ ๐ ๐ซ โ๏ธ ๐จ ๐ฒ), .include_router()
๐ค, โ๏ธ.
FastAPI ๐ ๐ช ๐ โซ๏ธ.
โคด๏ธ ๐ ๐ช โฒ ๐ ๐ (โ ๐ซ) โ app.dependency_overrides
๐ dict
:
app.dependency_overrides = {}
Tip
๐ฅ ๐ ๐ ๐ ๐ ๐ด โฎ๏ธ ๐ฏ, ๐ ๐ช โ ๐ โถ๏ธ ๐ฏ (๐ ๐ฏ ๐ข) & โฒ โซ๏ธ ๐ (๐ ๐ฏ ๐ข).