0Pricing
FastAPI Backend Development Bootcamp · درس

التبعيات العامة والتبعيات الفرعية

طبّق التبعيات على تطبيق كامل أو موجّه كامل، وسلِسل التبعيات الفرعية، وخزّن نتائج التبعيات مؤقتًا ضمن الطلب لبناء تطبيقات FastAPI نظيفة متعددة الطبقات.

التبعيات العامة والتبعيات الفرعية درس مجاني في FastAPI Backend Development Bootcamp على CoddyKit. هذا هو الدرس 4 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 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 user

Why 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 b

Modeling 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 dependencies list.
  • Chained sub-dependencies and relied on per-request caching.
  • Overrode dependencies for testing.

الأسئلة الشائعة

هل درس «التبعيات العامة والتبعيات الفرعية» مجاني؟

نعم — نص درس «التبعيات العامة والتبعيات الفرعية» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة FastAPI Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة FastAPI Backend Development Bootcamp 4 دروس في المجموع.

ماذا ستتعلم في «التبعيات العامة والتبعيات الفرعية»؟

طبّق التبعيات على تطبيق كامل أو موجّه كامل، وسلِسل التبعيات الفرعية، وخزّن نتائج التبعيات مؤقتًا ضمن الطلب لبناء تطبيقات FastAPI نظيفة متعددة الطبقات. تتمرن على FastAPI Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ FastAPI Backend Development Bootcamp؟

لا تُشترط خبرة سابقة. FastAPI Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 4.

كم من الوقت يستغرق درس «التبعيات العامة والتبعيات الفرعية»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس FastAPI Backend Development Bootcamp هذا؟

نعم. كل درس في FastAPI Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. فهم الاعتماديات في FastAPI
  2. حقن الاعتماديات الشائعة
  3. الاعتماديات القائمة على الأصناف واعتماديات Yield
  4. التبعيات العامة والتبعيات الفرعية
← العودة إلى FastAPI Backend Development Bootcamp