fastapi项目结构以及多进程部署

环境: python3.10.x Linux/centos

背景: 最近在用FastApi开发数据统计,并将统计数据返回给前端展示的数据系统。

数据库: mongodb, python包为mongoEngine

项目结构

haskell 复制代码
main.py
api
middleware
router
  -- __init__.py
  -- route.py
service
model
config

说明:

api: 接口的参数

model: 为数据库表映射对象

middleware: 中间件

router: 路由配置

service: 服务内容

config: 数据库等基础配置

其中 main.py 代码:

haskell 复制代码
from fastapi import FastAPI, APIRouter
import uvicorn

import multiprocessing
cpus = multiprocessing.cpu_count()

from router import route
app = FastAPI()

app.include_router(route.routers)

#uvicorn.run(app, host="0.0.0.0", port=8010) # 可用于开发时部署
if __name__ == "__main__":
    uvicorn.run(app="main:app", host="0.0.0.0", port=8010, workers= min(cpus,2))

route.py 代码:

haskell 复制代码
from fastapi import FastAPI, APIRouter
from api import filter
from model import  response_model

routers = APIRouter(prefix="/v1")

routers.add_api_route(path="/filter", endpoint=filter.filter_api, methods=["POST"],
        response_model=response_model.FilterResponseModel ,tags=["Home-filter"])

部署

在实际部署中,如以上main.py中所示, 采用 uvicorn.run, 并设置worker大于1,配置为多个进程运行。

备注:

关闭父进程以及相关子进程的方法:

haskell 复制代码
kill -TERM    ppid

ppid: 父进程的进程id

相关推荐
cup112 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi004 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵6 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf7 小时前
Agent 流程编排
后端·python·agent
copyer_xyf7 小时前
Agent RAG
后端·python·agent
copyer_xyf7 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf8 小时前
Agent 记忆管理
后端·python·agent
CaffeinePro21 小时前
Pydantic深度使用:数据校验、枚举、ORM映射
后端·fastapi
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python