依赖包
pip install python-dotenv
使用
#.env文件
ADMIN_EMAIL="[email protected]"
APP_NAME="ChimichangApp"
# config.py
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
app_name: str = "Awesome API"
admin_email: str
items_per_user: int = 50
class Config:
# 前提已经创建好了.env文件,数据将会自动映射到该配置类中
env_file = ".env" # 指定文件名
env_file_encoding = 'utf-8' # 指定编码
env_prefix = 'APP_' # 指定前缀
# 暴露一个对外的函数
@lru_cache()
def get_settings():
return config.Settings()
# main.py
from config import get_settings
@app.get("/info")
async def info(settings: Annotated[Settings, Depends(get_settings)]): # 作用于依赖项
return {
"app_name": settings.app_name,
"admin_email": settings.admin_email,
"items_per_user": settings.items_per_user,
}
标签:系列,读取,settings,FastAPI,app,get,per,env,name
From: https://www.cnblogs.com/weiweivip666/p/18041357