Dependencies
FastAPI has a very powerful but intuitive Dependency Injection system.
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
=
## Dependencies
return
=
return
return 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:
return In this case, this dependency expects:
- An optional query parameter
qthat is astr. - An optional query parameter
skipthat is anint, and by default is0. - An optional query parameter
limitthat is anint, and by default is100.
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:
return 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
Dependsa 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 leyendo una vista previa.
Inicia sesión para leer el artículo completo. Cualquier cuenta abre 4 artículos gratuitos al mes; el alumnado y el profesorado leen las páginas de su curso sin límite.
Iniciar sesión