Skip to main content

zhanshop-py

基于 FastAPI 的异步 Python 框架,把 Web API、MCP 工具、AI Agent 放在同一套业务代码上。

发行包名是 zhanshop-py,代码里的 import 名仍是 zhanshop。 PyPI 上另有一个名为 zhanshop 的包,与本项目无关;安装时请认准 zhanshop-py。

特性

  • Web:FastAPI + granian(ASGI),支持多 worker、uvloop、WebSocket、CORS、统一异常响应
  • 数据:asyncmy 异步 MySQL、SQLAlchemy async、链式查询构造器;Redis 连接池(hiredis 解析)
  • 安全:AES-256-GCM token、bcrypt 密码哈希
  • 任务:crontab 定时任务、自定义常驻进程、请求内后台任务、通用并发池
  • AI:LiteRuntime(只依赖 openai)/ AgnoRuntime 可切换;会话历史、知识库、SKILL.md 技能
  • MCP:把函数、模块、FastAPI 路由暴露成 MCP 工具,也能作为客户端连接远端 MCP
  • 配置:按 dev.ini / prod.ini 分环境加载,PY_ 前缀环境变量覆盖;config/ 声明式配置
  • 打包:docs/、scripts/、tests/ 不进入 wheel,安装后只有框架代码

环境要求

  • Python >= 3.12
  • Linux / macOS(uvloop 在 Windows 上不可用,Windows 未做验证)
  • MySQL 8+(使用数据库时)、Redis 6+(使用缓存时)

安装

pip install zhanshop-py

按需安装可选能力:

pip install "zhanshop-py[lite]"   # LiteRuntime,只依赖 openai
pip install "zhanshop-py[agno]"   # Agno 编排后端
pip install "zhanshop-py[mcp]"    # MCP 服务端 / 客户端
pip install "zhanshop-py[rag]"    # 知识库检索

lite 与 rag 都只依赖 openai;rag 单独列出是为了表达用途。


快速开始

目录结构

myapp/
├── server.py
├── dev.ini
├── config/
│   └── __init__.py
└── app/
    ├── __init__.py
    ├── exception/
    │   └── http_exception.py
    └── api/v1/controller/
        ├── __init__.py
        └── index.py

1. 入口 server.py

import os

from zhanshop.env import Env

# 读取 server.py 同目录下的 dev.ini / prod.ini
Env.init(os.path.abspath(__file__))

from zhanshop.console import Console
from zhanshop.server.server import Server

console = Console()
server = Server.getServer()
output = console.run(server)

if __name__ == "__main__" and output == server:
    Server.start()

APP_ENV=prod python server.py server start 会读取 prod.ini;不设置时读取 dev.ini。

2. 环境文件 dev.ini

[app]
name = myapp
# AES-256 密钥:32 字节原始字符串,或 64 位 hex
key = 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef
debug = 1

[database]
host = 127.0.0.1
port = 3306
user = root
password = change-me
dbname = myapp
charset = utf8mb4

[cache]
host = 127.0.0.1
port = 6379
password =
select = 0

[log]
level = INFO
max_files = 3

[server]
host = 0.0.0.0
port = 6201
worker = 1
backlog = 4096

Env.get() 的读取顺序是:PY_ 前缀的环境变量 > ini 文件 > 代码默认值。 例如容器里可以用 -e PY_server.port=9000 覆盖端口。

3. 配置 config/__init__.py

Config 会扫描 config 包的顶层属性,所以下面这些变量必须存在。实际项目可以按 app.py、server.py、route.py、database.py 等拆成多个模块,再在 config/__init__.py 里 import 进来。

from zhanshop.env import Env
from app.api.v1.controller import index

app = {
    "name": Env.get("app.name", "myapp"),
    "key": Env.get("app.key", ""),
    "version": "v1",
    "summary": "我的 API 服务",
    "description": "基于 zhanshop-py 的接口服务",
    "static": [],          # 静态目录名列表,对应 public/<name>
    "debug": bool(int(Env.get("app.debug", "0"))),
}

server = {
    "address": Env.get("server.host", "0.0.0.0"),
    "port": int(Env.get("server.port", "6201")),
    "workers": int(Env.get("server.worker", "1")),
    "backlog": int(Env.get("server.backlog", "4096")),
    "interface": "asgi",
    "log_level": "warn",
}

route = [
    {"router": index.router, "prefix": "/v1", "tags": ["示例"]},
]

database = {
    "default": "mysql",
    "connections": {
        "mysql": {
            "type": "mysql",
            "host": Env.get("database.host", "127.0.0.1"),
            "port": int(Env.get("database.port", "3306")),
            "user": Env.get("database.user", "root"),
            "password": Env.get("database.password", ""),
            "database": Env.get("database.dbname", "myapp"),
            "charset": "utf8mb4",
            "debug": False,
            "pool": {
                "min_connections": 10,
                "max_connections": 100,
                "pool_recycle": 600,
            },
        }
    },
}

cache = {
    "default": "default",
    "connections": {
        "default": {
            "host": Env.get("cache.host", "127.0.0.1"),
            "port": int(Env.get("cache.port", "6379")),
            "password": Env.get("cache.password", ""),
            "select": int(Env.get("cache.select", "0")),
            "timeout": 3,
            "pool": {"min_connections": 10, "max_connections": 100},
        }
    },
}

log = {"level": "INFO", "max_files": 3}

middleware = []   # FastAPI 中间件类
crontab = []      # 定时任务类
process = []      # 自定义常驻进程类
wsocket = {}      # WebSocket 路由
console = {}      # 自定义命令行

数据库和 Redis 的 pool 是必填项;缺少时启动阶段会直接报错。

4. 一个接口 app/api/v1/controller/index.py

from fastapi import APIRouter

router = APIRouter()

@router.get("/hello", summary="示例接口")
async def hello(name: str = "world"):
    return {"code": 0, "msg": "OK", "data": {"hello": name}}

5. 统一错误响应 app/exception/http_exception.py

框架的 Error.errorHandler 会尝试导入这个类,用它把异常包装成业务响应。建议项目 一开始就创建:

class HttpException:
    @staticmethod
    def handle(request, error):
        return {
            "code": error.code,
            "msg": error.msg,
            "data": None,
        }

6. 启动

python server.py server start
curl "http://127.0.0.1:6201/v1/hello?name=readme"
# {"code":0,"msg":"OK","data":{"hello":"readme"}}

常用能力

数据库

Db 默认使用 database.default 指定的连接:

from zhanshop.db import Db
from zhanshop.error import Error

class UserService:
    async def get_user(self, user_id: int):
        row = await (
            Db().table("system_user")
            .where({"user_id": user_id})
            .field("user_id, user_name, status")
            .find()
        )
        if row is None:
            Error.setError("用户不存在", 404)
        return dict(row)

    async def list_users(self, page: int = 1, size: int = 20):
        offset = (page - 1) * size
        return await (
            Db().table("system_user")
            .where({"status": 1})
            .order("user_id DESC")
            .limit(offset, size)
            .select()
        )

    async def create_user(self, data: dict):
        return await Db().table("system_user").insertGetId(data)

原生 SQL:

rows = await Db().query(
    "SELECT * FROM system_user WHERE status = :status",
    {"status": 1},
)

指定其他连接:

await Db().table("log", connection="log_mysql").insert(data)

Redis

from zhanshop.cache import Cache

await Cache().set("token:" + token, "1", ex=600)
exists = await Cache().get("token:" + token)
await Cache().delete("token:" + token)

Cache() 内部代理 redis.asyncio.Redis,Redis 的命令可以直接调用。连接池 decode_responses=False,读出来是 bytes,需要字符串时自行 decode()。

AES 与密码

from zhanshop.app import App
from zhanshop.helper.hash import Hash
from zhanshop.util.aes import Aes

# 密钥来自 config 的 app.key
token = App.get(Aes).encode_sync({"user_id": 1, "role_id": 9})
payload = App.get(Aes).decode_sync(token)

hashed = await Hash.hash_password("123456")
valid = await Hash.verify_password(hashed, "123456")

AES 使用 AES-256-GCM,token 格式为 base64url(nonce + ciphertext + tag)。 encode_sync / decode_sync 适合小数据;encode / decode 是异步版本, 大数据会切到线程池。

后台任务

在请求处理函数里添加,响应返回后由 FastAPI 执行:

from zhanshop.task import Task

@router.post("/users")
async def create_user(data: dict):
    user_id = await Db().table("system_user").insertGetId(data)
    Task.addTask(send_welcome_mail, user_id)
    return {"code": 0, "data": {"user_id": user_id}}

定时任务

# app/crontab/cleanup.py
class Cleanup:
    rule = "0 3 * * *"       # 每天 03:00
    async def execute(self):
        ...
# config/crontab.py
from app.crontab.cleanup import Cleanup

crontab = [Cleanup]

自定义常驻进程

# app/process/consumer.py
class Consumer:
    def execute(self):
        # 阻塞式循环;框架会为它单独起一个进程
        ...
# config/process.py
from app.process.consumer import Consumer

process = [Consumer]

并发池

用 ini 的 [pool.*] 声明容量,进程启动时绑定:

[pool.gpu]
capacity = 2
unit = slot
wait_timeout = 30
max_waiters = 10
allow_multi_worker = false
from zhanshop.pool import init_pools, load_specs, pool, shutdown_pools
from zhanshop.server.server import Server

@Server.onWorkerStart
async def _init_pools():
    init_pools(load_specs())

@Server.onWorkerStop
async def _close_pools():
    await shutdown_pools()

async def infer():
    async with pool("gpu").lease():
        ...
    # 或者一步执行阻塞函数
    return await pool("gpu").run(blocking_infer, image)

池容量是每进程一份。workers > 1 且存在未声明 allow_multi_worker = true 的池时,框架会在监听端口前直接报错,避免并发数被 worker 数悄悄放大。


AI Agent

安装:

pip install "zhanshop-py[lite]"
from zhanshop.ai import Agent, LiteRuntime, MemorySessionStore

def current_time() -> str:
    """返回当前时间,ISO 8601 格式。"""
    from datetime import datetime
    return datetime.now().isoformat(timespec="seconds")

runtime = LiteRuntime(
    model="qwen3.5-plus",
    api_key="sk-...",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    session_store=MemorySessionStore(max_runs=20),
)

agent = Agent(
    "assistant",
    instructions="回答保持一句话。",
    tools=[current_time],
    runtime=runtime,
)

result = agent.run("现在几点?", session_id="s-1")
print(result.content)

for event in agent.stream("再说一遍", session_id="s-1"):
    if event.event == "RunContent":
        print(event.content, end="", flush=True)
  • 工具写法和普通函数一样,参数 JSON Schema 由函数签名自动生成。
  • 同一 session_id 的 run / stream 串行执行,不同会话互不等待。
  • 要持久化历史,实现 SessionStore 的 history() / append() 即可。
  • 切 Agno:pip install "zhanshop-py[agno]",把 runtime 换成 AgnoRuntime(...), 其余代码不变。

声明式配置

# config/ai.py
agents = {
    "kefu": {
        "runtime": "lite",
        "model": {
            "provider": "dashscope",
            "id": "qwen3.5-plus",
        },
        "instructions": "你是客服助理。",
        "tools": ["app.tools"],
        "session": {"max_runs": 20},
    }
}
from zhanshop.ai import build_agents
from zhanshop.app import App
from zhanshop.config import Config

agents = build_agents(App.get(Config).get("ai.agents"))
agent = agents["kefu"]

知识库

from zhanshop.ai import MemoryKnowledgeBase, OpenAIEmbedder

kb = MemoryKnowledgeBase(
    OpenAIEmbedder("text-embedding-v4", api_key="sk-...", base_url="..."),
    k=4,
)
kb.add_text("退换货政策……")
kb.add_file("docs/faq.md")

agent = Agent("kefu", tools=[kb.as_tool()], runtime=runtime)

入库会调用嵌入接口,可以落盘快照,部署机器启动时直接载入:

kb.save("runtime/knowledge.json")
kb = MemoryKnowledgeBase(embedder).load("runtime/knowledge.json")

技能

from zhanshop.ai import AgentSpec, SkillSet

skills = SkillSet("app/skill")
spec = AgentSpec(
    name="kefu",
    instructions="你是客服助理。\n\n" + skills.catalog(),
    tools=skills.tools(),
)

技能目录里放 SKILL.md,模型先看目录,再按需读取全文或执行 scripts/ 下的脚本。


MCP

安装:

pip install "zhanshop-py[mcp]"

把函数、模块或 FastAPI 路由暴露成 MCP 工具:

from zhanshop.mcp import McpServer

server = McpServer("myapp")
server.add_module("app.tools")       # 扫描模块里所有 @tool
server.from_router(router)           # 只暴露带 @tool 的路由

server.serve()                       # stdio,给桌面客户端
# server.serve(transport="streamable-http", host="127.0.0.1", port=9000)

作为客户端连接远端 MCP:

from zhanshop.mcp import McpClient

client = McpClient("http://127.0.0.1:9000/mcp")
agent = Agent("kefu", tools=client.tools(), runtime=runtime)

client.tools() 返回统一的 ToolSpec,本地函数、远端 MCP 工具、HTTP 路由在 Agent 眼里没有区别。


部署

[server]
workers = 8
  • 每个 worker 是独立进程,各自持有一份数据库连接池、Redis 连接池和知识库。
  • 使用 [pool.*] 时保持 workers = 1,或显式声明 allow_multi_worker = true。
  • 日志默认写到 runtime/log/YYYYMMDD.log,按天切割。
  • app.debug = 0 时,未预期异常只返回“系统错误”,不泄露堆栈。

开发与测试

# 可编辑安装 + 开发依赖
pip install -e ".[dev]"

# 运行测试
pytest

没有安装 mcp / agno 时,相关用例会由 importorskip 自动跳过。

发布

本仓库使用 scripts/publish.py 交互式发布到 PyPI,具体步骤见仓库内 scripts/README.md。发布包名是 zhanshop-py,版本号一旦上传不可覆盖。

License

MIT

Metadata

Release files for zhanshop-py 2.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for zhanshop-py 2.0.1
File Size Uploaded Provenance Actions
zhanshop_py-2.0.1.tar.gz 70.5 kB Without provenance Details for zhanshop_py-2.0.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for zhanshop-py 2.0.1
File Interpreter ABI Platform Actions
zhanshop_py-2.0.1-py3-none-any.whl Python 3 none any Details for zhanshop_py-2.0.1-py3-none-any.whl

Total release size: 162.6 kB

Release files / zhanshop_py-2.0.1.tar.gz

Download URL zhanshop_py-2.0.1.tar.gz
Size 70.5 kB
Tags Source
SHA-256 checksum
How to use checksums
ae1c79c9c13be72c10fc21465e29e27b6e428e9cead24d9a07d8bc78581d963f
BLAKE2b-256 checksum
How to use checksums
5ca92cc863c37312c3bddebf3b37ccc92ad3db9275cb4d0f203e6e01ab0c24e9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.9

Release files / zhanshop_py-2.0.1-py3-none-any.whl

Download URL zhanshop_py-2.0.1-py3-none-any.whl
Size 92.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9f8c8688643dc548d6297f7dc7ee2d9ee50afc357b600b75759aa92df6cf5dd8
BLAKE2b-256 checksum
How to use checksums
6440971e4861565d63a5fb900ab72982fadc155c471699cbcedbc616d13e592b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.9

Security for zhanshop-py 2.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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