This commit is contained in:
18
config/app.py
Normal file
18
config/app.py
Normal file
@ -0,0 +1,18 @@
|
||||
from fastapi import FastAPI
|
||||
from config.settings import settings
|
||||
from api.v1.routers import api_router
|
||||
|
||||
def create_app(lifespan=None) -> FastAPI:
|
||||
app = FastAPI(
|
||||
title=settings.APP_NAME,
|
||||
debug=settings.DEBUG,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
# 注册路由
|
||||
app.include_router(api_router, prefix="/api/v1")
|
||||
|
||||
return app
|
||||
|
||||
|
||||
# app = create_app()
|
||||
18
config/database.py
Normal file
18
config/database.py
Normal file
@ -0,0 +1,18 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, scoped_session
|
||||
from config.settings import settings
|
||||
|
||||
SQLALCHEMY_SYNC_URL = (
|
||||
f"postgresql+psycopg://{settings.DB_USER}:{settings.DB_PASS}"
|
||||
f"@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}"
|
||||
)
|
||||
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_SYNC_URL,
|
||||
echo=False, # 开发可改 True
|
||||
future=True
|
||||
)
|
||||
|
||||
SessionLocal = scoped_session(
|
||||
sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
)
|
||||
22
config/env_loader.py
Normal file
22
config/env_loader.py
Normal file
@ -0,0 +1,22 @@
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
def load_env():
|
||||
"""
|
||||
自动根据 ENV 加载对应的 .env 文件
|
||||
"""
|
||||
base_file = ".env"
|
||||
prod_file = ".env.prod"
|
||||
test_file = ".env.test"
|
||||
|
||||
# 先加载基础 .env
|
||||
if os.path.exists(base_file):
|
||||
load_dotenv(base_file)
|
||||
|
||||
# 根据参数 ENV 再加载其他环境
|
||||
env = os.getenv("ENV", "dev")
|
||||
|
||||
if env == "prod" and os.path.exists(prod_file):
|
||||
load_dotenv(prod_file, override=True)
|
||||
elif env == "test" and os.path.exists(test_file):
|
||||
load_dotenv(test_file, override=True)
|
||||
33
config/settings.py
Normal file
33
config/settings.py
Normal file
@ -0,0 +1,33 @@
|
||||
from pydantic_settings import BaseSettings
|
||||
from pydantic import Field
|
||||
from config.env_loader import load_env
|
||||
|
||||
# 先加载 ENV & .env
|
||||
load_env()
|
||||
|
||||
class Settings(BaseSettings):
|
||||
# 环境
|
||||
ENV: str = Field("dev")
|
||||
DEBUG: bool = Field(True)
|
||||
TIMEZONE: str = Field("UTC")
|
||||
APP_NAME: str = Field("MemeApp")
|
||||
|
||||
# 日志
|
||||
LOG_LEVEL: str = Field("LOG_LEVEL")
|
||||
LOG_FILE_PATH: str = Field("logs")
|
||||
LOG_TYPE: str = Field("console")
|
||||
|
||||
# 数据库
|
||||
DB_HOST: str
|
||||
DB_PORT: int
|
||||
DB_USER: str
|
||||
DB_PASS: str
|
||||
DB_NAME: str
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
env_file_encoding = "utf-8"
|
||||
|
||||
|
||||
# 全局唯一配置实例
|
||||
settings = Settings()
|
||||
Reference in New Issue
Block a user