Document and test FastAPI integration #32
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
One of the goals of this project as shown in the README is to unify settings management for FastAPI. It would be helpful to provide a simple example of how to integrate fastenv with a FastAPI app. The most common use case for fastenv would be to load environment variables and settings when the FastAPI app starts up. The recommended way to customize app startup and shutdown is with lifespan events.
Changes
This PR will add an example to the quickstart in the README that uses lifespan events with lifespan state. Lifespan state is the recommended way to share objects between the lifespan function and API endpoints.
Currently, the lifespan function can only have one required argument for the FastAPI or Starlette app instance. This is because of the way Starlette runs the lifespan function. This is shown, but not explained, in the FastAPI docs on lifespan events - the code examples use objects from outside the lifespan function by instantiating them at the top-level of the module. Unfortunately this limits lifespan event customization. For example, an application might want a way to customize the dotenv file path or the object storage bucket from which the dotenv file needs to be downloaded. One way to customize the dotenv file path is to set an environment variable with the dotenv file path, then pass the environment variable value into
fastenv.load_dotenv()
. This is demonstrated in the new tests added here.The new tests will build on the example in the README by loading a dotenv file into a FastAPI app instance with
fastenv.load_dotenv()
. The resultantDotEnv
instance will then be accessed within an API endpoint by reading the lifespan state onrequest.state
. As explained in the Starlette lifespan docs, theTestClient
must be used as a context manager in order to run lifespan.Related