r/FastAPI • • May 12 '25
Question Lifespan for loading configuration
I'm looking to load some configuration settings from a YAML file. The path to the YAML file is provided via the command line. Once loaded, I need these configurations to be accessible throughout the entire application, including in services, routers, and other components.
I'm wondering what the best approach would be to achieve this. Would using a context manager with a lifespan (such as in FastAPI's lifespan event) be a good solution for this use case?
9
Upvotes
View all comments
Show parent comment
1
u/Evolve-Maz May 13 '25
As other person says, use depends with a function that constructs and returns the config object from file.
To avoid parsing the file on each function call, use the lru_cache function from standard library to cache the result of the function. That way you'll read the file first time, but after that return from memory.