Skip to main content

apiboot

为组件化构建 Api 服务而生的 Python 底层工具包。

  • 零依赖: dependencies = [], 所有第三方包 (httpx / pydantic / sqlalchemy / langchain / snowflake-id / PyMuPDF / APScheduler / redis / psutil) 都是可选, 用户项目自己 pip install 才用
  • 懒加载: import apiboot 不触发任何第三方包加载, 真正调用时才探测
  • Python 3.7+ 兼容: 不使用 PEP 604 (X | None)、PEP 585 (list[int])、海象、match/case 等 3.8+ 语法
  • FastAPI 友好: 提供统一响应中间件、错误体系、Schema 基类、CLI 守护进程管理

安装

pip install apiboot

按需安装可选依赖:

# HTTP / FastAPI 中间件
pip install httpx

# ORM / Schema
pip install sqlalchemy pydantic

# LLM
pip install langchain langchain-core

# OCR / 文档解析
pip install pymupdf

# MySQL / Redis / 调度
pip install sqlalchemy pymysql redis apscheduler

快速上手

1. 统一响应中间件

from fastapi import FastAPI
from apiboot.middlewares import JsonResponseMiddleware, ReqResLoggingMiddleware

app = FastAPI()
app.add_middleware(ReqResLoggingMiddleware)   # 日志外层
app.add_middleware(JsonResponseMiddleware)    # 响应包装内层

路由返回值自动包成 {"code": 200, "message": "成功", "data": {...}}。 异常自动捕获并包装成业务响应 (HTTP 200 + body code 区分业务/系统错误)。

2. 统一错误体系

from apiboot.error import ApiError, SystemError
from apiboot.error.code import NOT_FOUND

raise ApiError("uid 不能为空")                  # code = 20000 (默认)
raise ApiError("用户不存在", code=NOT_FOUND.code) # code = 12001
raise SystemError("数据库连接失败")               # code = 10099

3. Schema 基类 (驼峰自动转换)

from apiboot.schemas.base import BaseSchema

class UserSchema(BaseSchema):
    user_id: int
    user_name: str

u = UserSchema(user_id=1, user_name="alice")
u.model_dump(by_alias=True)   # {"userId": 1, "userName": "alice"}
u.model_dump(by_alias=False)  # {"user_id": 1, "user_name": "alice"}

populate_by_name=True 让前端 userId 和后端 user_id 双向都接受。

4. 流式响应队列 (SSE / WebSocket)

from apiboot.utils.queue_utils import StreamQueue
from fastapi.responses import StreamingResponse

channel = StreamQueue()

async def background():
    try:
        for chunk in llm.stream(prompt):
            await channel.put({"content": chunk})
    finally:
        channel.close()  # 推哨兵, 异常路径也会触发

asyncio.create_task(background())

@app.get("/stream")
async def stream():
    return StreamingResponse(channel.iter_sse(), media_type="text/event-stream")

5. .env 配置读取

from apiboot import config

print(config.PYPI_API_TOKEN)  # str
print(config.DB_PORT)         # int (自动类型转换)

支持多环境 (.env.development / .env.production), 自动类型转换 (str → int / bool / float)。

6. CLI 守护进程管理

abt start myproject      # 启动 (后台守护进程)
abt status               # 查看所有项目状态
abt stop myproject       # 优雅停止 (SIGTERM, 等 10s 兜底 SIGKILL)
abt restart myproject    # 重启
abt log myproject        # 实时 tail 日志
abt list                 # 列出所有注册项目

模块清单

模块 功能 可选依赖
apiboot.config .env 配置加载 + 类型转换 python-dotenv
apiboot.error 统一异常体系 (ApiError / HttpError / SystemError) + 错误码 -
apiboot.schemas.base pydantic Schema 基类, 自动 snake_case ↔ camelCase pydantic 2.0+
apiboot.schemas.json_result 统一响应格式 JsonResult[T] -
apiboot.schemas.page FastAPI 分页请求基类 pydantic
apiboot.middlewares.json_response 统一响应包装 + 异常捕获中间件 fastapi / httpx
apiboot.middlewares.req_res 请求/响应日志中间件 fastapi
apiboot.utils.http_utils 同步+异步 HTTP 客户端 (复用连接池) requests / httpx / aiohttp
apiboot.utils.datetime_utils 日期/时间戳/时区工具 -
apiboot.utils.file_utils 文件类型/文件名工具 -
apiboot.utils.path_utils 项目根目录/目录创建工具 -
apiboot.utils.image_utils PDF/PPTX → 图片 (PyMuPDF + LibreOffice) pymupdf
apiboot.utils.poi_utils PDF/PPTX/DOCX/Excel 解析器 pymupdf, python-docx, python-pptx, openpyxl, xlrd, pandas
apiboot.utils.snowflake_utils 雪花 ID 生成器 snowflake-id
apiboot.utils.obj_utils 对象 ↔ dict 互转 (pydantic / ORM / dataclass 自动识别) sqlalchemy, pydantic
apiboot.utils.queue_utils 异步流式队列 (SSE/WebSocket) -
apiboot.utils.base_utils 懒加载第三方模块工具 -
apiboot.llm LangChain chat model 一键构造 langchain, langchain-core
apiboot.llm.agent LangChain Agent 流式聊天封装 langchain
apiboot.ocr MinerU API 异步 OCR 客户端 httpx
apiboot.db.mysql MySQL sync/async 引擎 + CRUD sqlalchemy, pymysql/aiomysql/asyncmy
apiboot.db.redis Redis sync/async 连接 + KV 操作 redis
apiboot.cron APScheduler sync/async 调度器 apscheduler
apiboot.cli abt 守护进程管理 CLI psutil (可选)
apiboot.log 日志配置 (setup_logger / get_logger) -

开发

# 安装开发依赖
uv add --dev pytest

# 跑测试
uv run pytest tests/ -v

# 发版
uv run python scripts/upload_pypi.py --repository testpypi  # 先测试
uv run python scripts/upload_pypi.py                          # 正式

License

MIT

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

apiboot-0.1.4.tar.gz (146.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

apiboot-0.1.4-py3-none-any.whl (197.6 kB view details)

Uploaded Python 3

File details

Details for the file apiboot-0.1.4.tar.gz.

File metadata

  • Download URL: apiboot-0.1.4.tar.gz
  • Upload date:
  • Size: 146.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for apiboot-0.1.4.tar.gz
Algorithm Hash digest
SHA256 3c1e17aa31a22b423ed2044977c2c92861b9f08ed11d6a057af015903caa8595
MD5 5204817414dc882eeed7f9802ff4bb32
BLAKE2b-256 195b9bd82dc296bbee4c7c85d40f8bbd78968f81fc78a7c4b2faadb920f00d13

See more details on using hashes here.

File details

Details for the file apiboot-0.1.4-py3-none-any.whl.

File metadata

  • Download URL: apiboot-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 197.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for apiboot-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 d318e03d8526eca3ab36df1acde78931c212fe6aced15a0710dc7b1260086579
MD5 7a4f8954329a247a8b0d519fe4d98cf9
BLAKE2b-256 ecafba1270b653a6ae5650a9101b680c6cfe66d18958cb75251144159bd4e3fe

See more details on using hashes here.

Release history Release notifications | RSS feed

0.1.10

2 files

0.1.9

2 files

0.1.8

2 files

0.1.7

2 files

0.1.6

2 files

0.1.5

2 files

This release

0.1.4 This release

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

0.0.1

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page