42 lines
1.6 KiB
Python
42 lines
1.6 KiB
Python
# ============================================================
|
|
# 项目入口主文件 — FastAPI 应用启动与路由装配
|
|
# 职责:
|
|
# 1. 初始化 ORM 引擎,自动建表
|
|
# 2. 创建 FastAPI 实例并配置跨域中间件
|
|
# 3. 挂载 API 路由和 HTTP 请求日志中间件
|
|
# 4. 通过 uvicorn 启动服务
|
|
# ============================================================
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from database import engine, Base
|
|
from api.statistics_api import BasicInformationAPI
|
|
from HttpLog import m1
|
|
from model import statistics_model # 必须导入,触发 SQLAlchemy 把模型注册到 Base.metadata
|
|
|
|
# 根据 model 中定义的 ORM 模型,在数据库中创建所有表(若已存在则跳过)
|
|
Base.metadata.create_all(engine)
|
|
|
|
# 创建 FastAPI 应用实例
|
|
app = FastAPI()
|
|
|
|
# 配置跨域中间件:允许任意来源、任意方法、任意请求头
|
|
# 解决前端开发时浏览器的同源策略拦截问题
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# 将统计分析模块的路由挂载到主应用,所有路由前缀在路由文件内定义
|
|
app.include_router(BasicInformationAPI)
|
|
|
|
# 注册 HTTP 请求日志中间件:对每一次请求记录方法、地址、参数、响应和耗时
|
|
app.middleware('http')(m1)
|
|
|
|
# 直接运行本文件时,用 uvicorn 启动开发服务器
|
|
# 地址:http://127.0.0.1:12345
|
|
if __name__ == '__main__':
|
|
import uvicorn
|
|
uvicorn.run("main:app", host='127.0.0.1', port=12345) |