@ -23,6 +23,8 @@ In fact, FastAPI uses those two decorators internally.
///
And if you have a context manager already, you can use it as a dependency, too.
## A database dependency with `yield`
For example, you could use this to create a database session and close it after finishing.
@ -240,36 +242,37 @@ When the `with` block finishes, it makes sure to close the file, even if there w
When you create a dependency with `yield`, **FastAPI** will internally create a context manager for it, and combine it with some other related tools.
### Using context managers in dependencies with `yield`
### Context Managers as dependencies
/// warning
You don’t have to create a Context Manager to use FastAPI dependencies.
This is, more or less, an "advanced" idea.
But sometimes you might want to use a dependency both inside and outside FastAPI. For example, you might want to connect to a database in a DB migration script. You can create a Context Manager manually then:
If you are just starting with **FastAPI** you might want to skip it for now.
This way you can use it with `Depends()` in your app, and as a regular Context Manager everywhere else:
In Python, you can create Context Managers by <ahref="https://docs.python.org/3/reference/datamodel.html#context-managers"class="external-link"target="_blank">creating a class with two methods: `__enter__()` and `__exit__()`</a>.
* <ahref="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager"class="external-link"target="_blank">`@contextlib.contextmanager`</a> or
If you are just starting with **FastAPI** you might want to skip it for now.
///
You can also create Context Managers by <ahref="https://docs.python.org/3/reference/datamodel.html#context-managers"class="external-link"target="_blank">creating a class with two methods: `__enter__()` and `__exit__()`</a>.
using them to decorate a function with a single `yield`.
Like the Context Managers created with `contextlib`, you can use them inside of **FastAPI** dependencies directly:
That's what **FastAPI** uses internally for dependencies with `yield`.
But you don't have to use the decorators for FastAPI dependencies (and you shouldn't).
/// note | Technical Details
FastAPI will do it for you internally.
Internally, FastAPI calls the dependency function and then checks if the result has either an `__enter__()` or an `__aenter__()` method. If that’s the case, it will treat it as a context manager.