> For the complete documentation index, see [llms.txt](https://meetbill.gitbook.io/butterfly-user-doc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://meetbill.gitbook.io/butterfly-user-doc/readme.md). Agents can also search and read this documentation through its [MCP server](https://meetbill.gitbook.io/butterfly-user-doc/~gitbook/mcp).

# Introduction

{% hint style="info" %}
完美，不是在没有什么需要增加，而是在没有什么需要的时候去掉。
{% endhint %}

Python 轻量 web 框架 butterfly

```
    __          __  __            ______
   / /_  __  __/ /_/ /____  _____/ __/ /_  __
  / __ \/ / / / __/ __/ _ \/ ___/ /_/ / / / /
 / /_/ / /_/ / /_/ /_/  __/ /  / __/ / /_/ /
/_.___/\__,_/\__/\__/\___/_/  /_/ /_/\__, /
                                    /____/
```

Butterfly（轻量化 WSGI web 应用程序框架）如同蝴蝶一样，小而美，简单可依赖。目的是让入门变得简单快捷，能够扩展到复杂的应用程序。

{% hint style="info" %}
当前版本：`1.4.2.2`。支持 Python 2.7 与 Python 3.x，并已完成 Python 3.12 兼容；新项目推荐使用 Python 3。
{% endhint %}

> * 接入 --- 【接入】函数快速适配：普通 Python 函数可快速升级为 butterfly handler
> * 模型 --- 【模型】数据库支持：自带 ORM, 支持存储数据到 MySQL,Redis,LocalCache
> * 异步 --- 【百川】任务异步处理：任一 butterfly handler 皆可消费，异步处理 MQ 中消息
> * 定时 --- 【如期】任务定时调度：设置 butterfly handler 执行时间，定期执行 handler
> * 编排 --- 【星桥】任务依赖编排：设置 butterfly handler 依赖顺序，有序编排 handler
> * 路由 --- 【RESTful】风格路由：支持静态路由与动态路由（`/user/:user_id`），并按 GET/POST/PUT/DELETE 等方法区分
> * 校验 --- 【Schema】字段声明校验：`xlib.schema` 自动完成类型转换、必填校验和 camelCase ↔ snake\_case 转换
> * 观测 --- 【追踪】全链路可观测：内置 Prometheus `/metrics`，并支持 W3C `traceparent` 与 32 位 trace\_id 全链路串联
> * 加载 --- 【角色】按角色加载：通过 `APP_ROLE` 与 `conf/role_handlers.py` 只加载指定角色需要的 handler 包

```
#################################################################################################<1 接入 >##
+common func----------------------------+    +butterfly handler-----------------------------------------+
|                                       |    |     ---------------(1) 增加装饰器标识 api 类型
|                                       |    |    /            ---(2) 增加 req 参数（Request 对象）
|                                       |    |   /           /
|                                       |    |@funcattr.api /
|def hello(str_info):                   |===>|def hello(req, str_info):
|    ...                                |    |    ...
|    return "OK", {"str_info": str_info}|    |    return "OK", {"str_info": str_info}
|                                       |    |    ----------------------------------
|                                       |    |    (3) 返回 stat/int, [data 可选 ], [headers 可选 ]
+---------------------------------------+    +------------------+-----------------------------+---------+
################################################################|#############################|##<2 模型 >##
                                                                |                             |
                                        +----------+------------V--------------------+        |
                                        |  Media   |             Usage               |        |
                                        +----------+---------------------------------+        |
                                        |  MySQL   | ORM,Native method               |        |
                                        +----------+---------------------------------+        |
                                        |  Redis   | ORM,Native method,Baidu RAL     |        |
                                        +----------+---------------------------------+        |
                                        |Localcache| set/get ...                     |        |
                                        +----------+---------------------------------+        |
##############################################################################################|##<3 异步 >##
                  +Redis(message queue)-----------------------------------------+             |
                  | +msg------------------------+                               |             |
                  | |'{"str_info":"helloworld"}'|                               |             |
                  | +-+-------------------------+                               |             |
                  |   |       +queue-----------------------------+              |             |
                  |   +------>|         /demo_api/hello          |<---------+   |             |
                  |    lpush  +----------------------------------+   rpop   |   |             |
                  |                               +-------------------------+-+ |             |
                  |                               |'{"str_info":"helloworld"}'| |<------------+
                  |                               +---------------------------+ |
                  +-^-------------------^---------------------------------------+
####################|###################|########################################################<4 定时 >##
                                        |
        +-----------+----------+        |
        |         ruqi         |        |
        +----------------------+        |
########################################|########################################################<5 编排 >##
                                        |
                            +taskflow---+---------------------------+
                            |                    +Task------------+ |
                            |                +---|/{app}/{handler}| |
                            |                |   +----------------+ |
                            | +Job-------+   |   +Task------------+ |
                            | |          +---+---|/{app}/{handler}| |
                            | +----------+   |   +----------------+ |
                            |                |   +Task------------+ |
                            |                +---|/{app}/{handler}| |
                            |                    +----------------+ |
                            |               xingqiao                |
                            +---------------------------------------+
```

## handler 返回值

handler 的返回值由 `xlib/protocol_json_static.py` 统一解析，支持以下形式：

```python
# 1) 只返回状态码（stat 字符串或 HTTP 整数）
return "OK"
return 200

# 2) 返回 (stat, data)
return "OK", {"str_info": "hello"}

# 3) 返回 (stat, data, headers)
return "OK", {"str_info": "hello"}, [("demo", "1.0.1")]
```

* 使用 `@funcattr.api` 等 JSON 编码装饰器时，`stat` 会写入响应体的 `stat` 字段，`data` 必须为 `dict` 或 `None`；RESTful 返回整数状态码时不再注入 `stat`，可返回其他可 JSON 序列化内容。
* 使用 `@funcattr.api_download` 时，handler 返回 `(stat, {"filename": ..., "is_download": ...}, headers)`，由 `protocol_file` 读取文件并封装 404/403、MIME 与 Content-Length。
* 未加装饰器（不编码响应）时，第一个返回值是 HTTP 状态码（int），`data` 为响应内容，`headers` 为响应头列表。
* RESTful handler（`@funcattr.api_path`）返回整数状态码时，该整数会直接作为 HTTP 状态码透传。

## 运行入口与环境变量

`run.sh` 是统一启动入口，默认加载 `butterfly/.env`；`.env` 中与 shell 同名的变量以 `.env` 为准（`ENV_FILE` 本身除外）：

```bash
# 默认（Python 2.7 + 内置 cherrypy backend）
bash run.sh start

# 使用 Python 3
PYTHON_BIN=python3 bash run.sh start
bash run_python3.sh start          # 兼容入口，等价于 PYTHON_BIN=python3 bash run.sh

# 指定 env 文件
ENV_FILE=/path/to/dev.env bash run.sh start

# 使用 gunicorn backend（建议固定 Python 3）
SERVER_BACKEND=gunicorn GUNICORN_PYTHON_BIN=python3 bash run.sh start
```

常用环境变量：

| 变量                          | 说明                                         | 默认值                   |
| --------------------------- | ------------------------------------------ | --------------------- |
| `SERVER_ID`                 | 参与 trace\_id 加密体生成，必须为 2 个字符，否则回退为 `BF`    | `BF`                  |
| `POD_NAME`                  | Pod/实例名，参与 trace\_id 高位编码                  | 空                     |
| `APP_ROLE`                  | 当前实例角色，配合 `ROLE_HANDLERS` 加载 handler       | 空（加载全部）               |
| `SERVER_REQUEST_QUEUE_SIZE` | HTTP 请求队列大小                                | `128`                 |
| `SERVER_BACKEND`            | Web server backend：`cherrypy` 或 `gunicorn` | `cherrypy`            |
| `PYTHON_BIN`                | cherrypy backend 使用的 Python 解释器            | `python2.7`           |
| `GUNICORN_PYTHON_BIN`       | gunicorn 使用的 Python 解释器                    | `python3`             |
| `SCHEDULER_LOCK_PATH`       | scheduler 进程间单例锁路径                         | `data/scheduler.lock` |

## 了解更多

> * [Butterfly 架构说明](https://github.com/meetbill/butterfly/blob/master/docs/ARCHITECTURE.md)
> * [Butterfly 用户手册](https://meetbill.gitbook.io/butterfly-user-doc)
> * [Butterfly 进阶手册](https://meetbill.gitbook.io/butterfly-project-doc)
> * [Butterfly 示例](https://github.com/meetbill/butterfly-examples)
