fastapi: 第十五章:读取.env文件

一,安装用到的第三方库:

$ pip install pydantic-settings

 

二,代码

1,配置文件

APP_NAME="My FastAPI App"
LOGS_DIR="/data/fastapi/test123/logs"
ITEMS_PER_PAGE=20

2,获取代码:

# app/core/Setttins.py
from pydantic_settings import BaseSettings, SettingsConfigDict
from functools import lru_cache

# 1. 定义配置模型
class Settings(BaseSettings):
    app_name: str
    logs_dir: str
    items_per_page: int = 10  # 设置默认值

    # 读取 .env 文件的配置
    model_config = SettingsConfigDict(env_file=".env")

# 2. 使用 lru_cache 缓存配置,避免重复读取文件
@lru_cache
def get_settings():
    return Settings()

 

3,访问:

# app/api/users.py
from fastapi import APIRouter

from app.core.Settings import get_settings
from app.core.logger import logger

# 创建路由器实例
# prefix:所有路由的统一前缀,避免重复写"/users"
# tags:在Swagger文档中分组显示
router = APIRouter(prefix="/users", tags=["用户管理"])

@router.get("/all")
def get_all_users():

    # 💡 直接在函数体内调用,不再作为参数传入
    settings = get_settings()

    return {
        "app_name": settings.app_name,
        "logs_dir": settings.logs_dir,
        "items_per_page": settings.items_per_page
    }

三,测试效果 

image

posted @ 2026-06-10 15:20  刘宏缔的架构森林  阅读(7)  评论(0)    收藏  举报