การพึ่งพาระดับส่วนกลางและการพึ่งพาย่อย
ใช้การพึ่งพากับทั้งแอปหรือเราเตอร์ เชื่อมต่อการพึ่งพาย่อยเป็นลำดับ และแคชผลลัพธ์การพึ่งพาภายในคำขอ เพื่อสร้างแอปพลิเคชัน FastAPI ที่สะอาดและแบ่งเป็นชั้น
การพึ่งพาระดับส่วนกลางและการพึ่งพาย่อย เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Scaling Up Dependencies
You can attach a dependency to a single route, but real apps need to apply checks broadly. FastAPI supports dependencies at the app, router, and route levels, plus dependencies that depend on other dependencies.
App-Level Dependencies
Pass dependencies=[...] to the FastAPI constructor to run them for every request. Useful for global logging or API-key checks.
from fastapi import FastAPI, Depends
async def verify_key():
...
app = FastAPI(dependencies=[Depends(verify_key)])Router-Level Dependencies
Attach dependencies to an APIRouter so they apply to every route in that router but not the whole app.
from fastapi import APIRouter, Depends
admin = APIRouter(
prefix='/admin',
dependencies=[Depends(verify_admin)],
)Dependencies Without a Return
When you only need a side effect (like raising on failure), put the dependency in the dependencies list rather than a parameter. Its return value is ignored.
@app.get('/secure', dependencies=[Depends(verify_key)])
async def secure():
return {'ok': True}Sub-Dependencies
A dependency can itself depend on another dependency. FastAPI resolves the whole chain automatically.
def get_token(authorization: str = Header(None)):
return authorization
def get_user(token: str = Depends(get_token)):
return lookup_user(token)
@app.get('/me')
async def me(user = Depends(get_user)):
return userWhy Layer Dependencies
Sub-dependencies let you compose small, single-purpose pieces: parse the token, then resolve the user, then check permissions. Each layer is reusable and independently testable.
Dependency Caching
Within a single request, FastAPI caches each dependency by default. If two dependencies both need get_user, it runs only once. Disable with Depends(fn, use_cache=False).
@app.get('/data')
async def data(
a = Depends(get_user),
b = Depends(get_user), # reuses cached result
):
return a is bModeling the Resolution Chain
The resolver walks dependencies depth-first and caches by function. Here is a simplified version in plain Python.
cache = {}
calls = []
def resolve(name):
if name in cache:
return cache[name]
calls.append(name)
cache[name] = name + '_value'
return cache[name]
resolve('get_user'); resolve('get_user'); resolve('get_token')
print(calls)Combining Levels
Precedence flows from broad to narrow: app dependencies run first, then router, then route. A request to a router route runs all three layers in order.
Overriding for Tests
Swap any dependency in tests with app.dependency_overrides to inject fakes without touching production code.
app.dependency_overrides[get_user] = lambda: {'id': 1, 'name': 'Test'}Best Practices
Keep dependencies focused:
- One responsibility per dependency.
- Use app/router level for cross-cutting concerns.
- Rely on caching; only disable it when you truly need fresh evaluation.
Quick Check
Two parameters in the same route both use Depends(get_user) with default settings. How many times does get_user run for one request?
Recap
You leveled up dependency injection:
- Applied dependencies at app, router, and route scope.
- Used side-effect-only dependencies in the
dependencieslist. - Chained sub-dependencies and relied on per-request caching.
- Overrode dependencies for testing.
เรียนรู้ FastAPI Backend Development Bootcamp ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 21
- บทเรียน
- 84
คำถามที่พบบ่อย
บทเรียน “การพึ่งพาระดับส่วนกลางและการพึ่งพาย่อย” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การพึ่งพาระดับส่วนกลางและการพึ่งพาย่อย” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การพึ่งพาระดับส่วนกลางและการพึ่งพาย่อย”
ใช้การพึ่งพากับทั้งแอปหรือเราเตอร์ เชื่อมต่อการพึ่งพาย่อยเป็นลำดับ และแคชผลลัพธ์การพึ่งพาภายในคำขอ เพื่อสร้างแอปพลิเคชัน FastAPI ที่สะอาดและแบ่งเป็นชั้น คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “การพึ่งพาระดับส่วนกลางและการพึ่งพาย่อย” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ทำความเข้าใจการพึ่งพาใน FastAPI
- การฉีดการพึ่งพาทั่วไป
- การพึ่งพาแบบใช้คลาสและ Yield
- การพึ่งพาระดับส่วนกลางและการพึ่งพาย่อย