Skip to content

How to inject Fastenv to FastAPI methods #28

Answered by br3ndonland
clabnet asked this question in Q&A
Discussion options

You must be logged in to vote

Thanks for your interest @clabnet. It's a good question and I was thinking I should write some docs to more clearly explain this topic.

I agree with your suggestion of using a lifespan event. I would just modify it slightly. To access your DotEnv model after the application starts up, maybe you could set it as an attribute on your FastAPI instance.

from contextlib import asynccontextmanager

import fastenv
from fastapi import FastAPI


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Load .env file"""
    settings = await fastenv.load_dotenv(".env", find_source=True)
    app.settings = settings
    yield


app = FastAPI(lifespan=lifespan)

Let me know how it goes.

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@clabnet
Comment options

@br3ndonland
Comment options

Answer selected by clabnet
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants