app.state.config.debug after running this code?from fastapi import FastAPI from pydantic import BaseSettings class Settings(BaseSettings): debug: bool = False app = FastAPI() @app.on_event("startup") async def startup_event(): app.state.config = Settings(debug=True) # After startup event, what is app.state.config.debug?
The startup_event runs when the app starts and sets app.state.config to a Settings instance with debug=True. So app.state.config.debug is True.
.env?from pydantic import BaseSettings class Settings(BaseSettings): app_name: str = "MyApp" debug: bool = False # How to load .env file automatically?
To load environment variables from a file, Pydantic requires setting env_file inside a nested Config class.
config.app_name after this FastAPI app runs?app.state. What will config.app_name print?from fastapi import FastAPI from pydantic import BaseSettings class Settings(BaseSettings): app_name: str = "DefaultApp" app = FastAPI() @app.on_event("startup") async def startup(): app.state.config = Settings(app_name="CustomApp") config = app.state.config print(config.app_name)
app.state.config is set versus when config is assigned.The assignment config = app.state.config happens before the startup event runs, so app.state.config does not exist yet. This causes an AttributeError.
from fastapi import FastAPI from pydantic import BaseSettings class Settings(BaseSettings): debug: bool = False class Config: env_file = ".env" app = FastAPI() @app.on_event("startup") async def startup(): app.state.config = Settings() # .env file contains DEBUG=true
Pydantic loads the .env file relative to the current working directory. If the .env file is not in that directory, variables won't load and defaults are used.
Using a single Pydantic BaseSettings class with environment variables loaded from different .env files per environment is the best practice. It keeps code clean and allows easy switching between environments.