Escriu per cercar…

Dependencies

FastAPI has a very powerful but intuitive Dependency Injection system.

S'ensenya a
Desenvolupament web en entorn servidorServidor webDAW-BIOProgramació orientada a objectesInterfície web amb FastAPIPYTHON

Introduction

“Dependency Injection” means, in programming, that there is a way for your code (in this case, your path operation functions) to declare things that it requires to work and use: “dependencies”.

And then, that system will take care of doing whatever is needed to provide your code with those necessary dependencies (“inject” the dependencies).

This is invaluable when you need to:

  • Have shared logic (the same code logic again and again).
  • Share database connections.
  • Enforce security, authentication, role requirements, etc.
  • And many other things…

All these, while minimizing code repetition.

Function Dependency

python
from typing import Annotated

from fastapi import APIRouter, Depends

router = APIRouter()

## Dependencies

async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

CommonsDep = Annotated[dict, Depends(common_parameters)]

@router.get("/author")
async def author_get(commons: CommonsDep):
    return [{"author": id} for id in range(commons["skip"], commons["skip"] + commons["limit"])]

@router.get("/book")
async def book_get(commons: Annotated[dict, Depends(common_parameters)]):
    return [{"book": id} for id in range(commons["skip"], commons["skip"] + commons["limit"])]

Create a dependency, or “dependable”

Our dependency it’s just the function common_parametersthat can take all the same parameters that a path operation function can take:

python
async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

In this case, this dependency expects:

  • An optional query parameter q that is a str.
  • An optional query parameter skip that is an int, and by default is 0.
  • An optional query parameter limit that is an int, and by default is 100.

And then it just returns a dict containing those values.

Declare the dependency, in the “dependant”

The same way you use Body, Query, etc. with your path operation function parameters, use Depends with a new parameter:

python
@router.get("/author")
async def author_get(commons: Annotated[dict, Depends(common_parameters)]):
    return [{"author": id} for id in range(commons["skip"], commons["skip"] + commons["limit"])]

Although you use Depends in the parameters of your function the same way you use Body, Query, etc., Depends works a bit differently.

  • You only give Depends a single parameter.
  • This parameter must be something like a function.
  • You don’t call it directly (don’t add the parenthesis at the end), you pass it as a parameter to Depends().
  • And that function takes parameters in the same way that path operation functions do.

Whenever a new request arrives, FastAPI will take care of:

  • Calling your dependency (“dependable”) function with the correct parameters.
  • Get the result from your function.
  • Assign that result to the parameter in your path operation function.

Estàs llegint una vista prèvia.

Inicia sessió amb Google per llegir la pàgina completa.

Inicia sessió amb Google

Amb qualsevol compte de Google. Només et demanarem que acceptis les condicions del servei.