fastapi:命令行共享web的.env解析

一,代码:

.env

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

解析类:

# 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()

命令行代码:

# app/commands/calc_util.py

# app/commands/calc_util.py
import typer
# 引入 Web 和 CLI 共用的业务逻辑
# from app.services.user_service import create_user_in_db
from app.core.Settings import get_settings

app = typer.Typer()

# 1. 使用装饰器定义另一个名为 "calc" 的命令
@app.command()
def calc1(x: int, y: int):
    """
    计算两个整数的和。
    """
    typer.echo(f"计算结果: {x} + {y} = {x + y}")

# 2. 使用装饰器定义另一个名为 "get_config" 的命令
@app.command()
def get_config():
    """
    查看当前 CLI 读取到的 Web 配置(测试共享是否成功)
    """
    settings = get_settings()
    print(settings)
    typer.echo(f"项目名称: {settings.app_name}")
    typer.echo(f"日志目录: {settings.logs_dir}")

二,测试效果:

$ python run_cli.py calc_util get-config
app_name='My FastAPI App' logs_dir='/data/fastapi/test123/logs' items_per_page=20
项目名称: My FastAPI App
日志目录: /data/fastapi/test123/logs

 

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