from fastapi import FastAPI from contextlib import asynccontextmanager from apps.urls import api_router from database import engine, get_db from models import Base from init_data import init_all_data @asynccontextmanager async def lifespan(app: FastAPI): # 启动时初始化数据库 async with engine.begin() as conn: # 创建所有表 await conn.run_sync(Base.metadata.create_all) # 初始化数据 async for db in get_db(): await init_all_data(db) break yield # 关闭时的清理工作 await engine.dispose() # 实例化FastAPI app = FastAPI( title="Book System API", description="图书系统API", version="1.0.0", lifespan=lifespan ) # 包含路由 app.include_router(api_router) # 声明装饰器方法和路径 @app.get("/") # 声明装饰器函数 async def home(): return {"message": "Hello World!!!"} # 如果使用命令行启动,使用uvicorn 文件名:app --reload启动即可,下面命令就不用写 # 如果写下面的命令,就不需要命令行启动了,直接用IDE运行即可 if __name__ == "__main__": import uvicorn import os name = f"{os.path.splitext(os.path.basename(os.path.abspath(__file__)))[0]}:app" uvicorn.run(name, host="0.0.0.0", port=8000, reload=True, reload_dirs=["_"])