FastAPI系列:环境配置读取

依赖包

pip install python-dotenv

使用

#.env文件
ADMIN_EMAIL="deadpool@example.com"
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,
    }
posted @ 2024-02-28 18:09  我在路上回头看  阅读(162)  评论(0编辑  收藏  举报