diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7e67fd3 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,45 @@ +# 使用Python 3.10作为基础镜像 +FROM python:3.10-slim + +# 设置时区 +RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime +# 清空所有默认源 +RUN rm -rf /etc/apt/sources.list.d/* && \ + rm -f /etc/apt/sources.list + +# 替换为阿里云源 +RUN echo "\ + deb https://mirrors.aliyun.com/debian/ bookworm main non-free-firmware contrib\n\ + deb-src https://mirrors.aliyun.com/debian/ bookworm main non-free-firmware contrib\n\ + deb https://mirrors.aliyun.com/debian/ bookworm-updates main non-free-firmware contrib\n\ + deb-src https://mirrors.aliyun.com/debian/ bookworm-updates main non-free-firmware contrib\n\ + deb https://mirrors.aliyun.com/debian/ bookworm-backports main non-free-firmware contrib\n\ + deb-src https://mirrors.aliyun.com/debian/ bookworm-backports main non-free-firmware contrib\n\ + deb https://mirrors.aliyun.com/debian-security bookworm-security main non-free-firmware contrib\n\ + deb-src https://mirrors.aliyun.com/debian-security bookworm-security main non-free-firmware contrib\n\ + " > /etc/apt/sources.list + +# 安装系统依赖 +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + build-essential \ + default-libmysqlclient-dev \ + pkg-config \ + && rm -rf /var/lib/apt/lists/* + +# 设置工作目录 +WORKDIR /app + +# 复制项目文件 +COPY requirements.txt . +COPY app app/ + +# 安装Python依赖 +RUN pip install -i https://mirrors.aliyun.com/pypi/simple/ -r requirements.txt \ + && pip install uvicorn + +# 暴露端口 +EXPOSE 8000 + +# 启动命令 +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] \ No newline at end of file diff --git a/main.py b/main.py index e9b84a5..1592e77 100644 --- a/main.py +++ b/main.py @@ -4,11 +4,22 @@ from app.core.config import settings from app.api.v1.api import api_router from app.core.middleware import add_response_middleware from app.core.exceptions import add_exception_handlers +from contextlib import asynccontextmanager + +@asynccontextmanager +async def lifespan(app: FastAPI): + # 在应用启动时执行 + from app.db.init_db import init_db + await init_db() + yield + # 在应用关闭时执行 + # 清理代码可以放在这里 app = FastAPI( title=settings.PROJECT_NAME, description=settings.PROJECT_DESCRIPTION, version=settings.PROJECT_VERSION, + lifespan=lifespan ) # 配置CORS @@ -37,14 +48,6 @@ async def root(): async def health_check(): return {"status": "healthy"} -# 应用启动事件 -@app.on_event("startup") -async def startup_event(): - # 延迟导入,避免循环导入问题 - from app.db.init_db import init_db - # 调用异步初始化函数 - await init_db() - if __name__ == "__main__": import uvicorn uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) \ No newline at end of file