Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document and test FastAPI integration #32

Merged
merged 1 commit into from
Apr 11, 2024
Merged

Document and test FastAPI integration #32

merged 1 commit into from
Apr 11, 2024

Conversation

br3ndonland
Copy link
Owner

@br3ndonland br3ndonland commented Apr 11, 2024

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 resultant DotEnv instance will then be accessed within an API endpoint by reading the lifespan state on request.state. As explained in the Starlette lifespan docs, the TestClient must be used as a context manager in order to run lifespan.

Related

Copy link

vercel bot commented Apr 11, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
fastenv ✅ Ready (Inspect) Visit Preview Apr 11, 2024 7:55pm

@br3ndonland br3ndonland merged commit 7362541 into develop Apr 11, 2024
10 checks passed
@br3ndonland br3ndonland deleted the fastapi branch April 11, 2024 20:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant