FrameworkBenchmarks 中的 uWSGI 基准测试:基于 Python WSGI 的 JSON 与 Plaintext 性能压测实现解析
FrameworkBenchmarks 中的 uWSGI 基准测试:基于 Python WSGI 的 JSON 与 Plaintext 性能压测实现解析
导读
本文围绕 TechEmpower FrameworkBenchmarks(TFB)仓库中 frameworks/Python/uwsgi 目录下的 uWSGI 基准测试实现展开,系统讲解 uWSGI 在 TFB 测试套件中的定位、/json 与 /plaintext 两个测试路径的应用源码、uwsgi.ini 与 nginx.conf 的性能调优配置、两种部署形态(uWSGI 直连与 nginx + uWSGI 组合)的 Docker 启动方式,以及 TFB 工具链对这两个测试类型的自动化验证规则。读完本文,你将掌握 uWSGI 在无数据库(database: None)场景下如何参与 Web 框架横向对比,并能理解仓库中每个配置文件与启动参数的真实作用。
uWSGI 测试在 TFB 套件中的定位
在 TFB 仓库中,每个框架目录都以一个 benchmark_config.json 描述其可参与的测试变体。uWSGI 被归类为 "Platform"(平台类)、语言为 Python、数据库为 "None"、ORM 为 "Raw",即不依赖任何 ORM 与数据库连接,仅提供纯计算型 HTTP 服务。仓库根目录的 Python README 明确指出,Python 生态在 TFB 中常用的 WSGI 服务器组合包括 "Nginx + uWSGI",推荐使用 UNIX 域套接字在 nginx 与 uWSGI 之间通信,以规避额外的 TCP/IP 开销——这正是本测试目录中 nginx-uwsgi 变体的设计来源。
uWSGI 测试目录的 README.md 给出了测试路径清单:只有 JSON Serialization(/json) 被实现,而 Single Database Query、Multiple Database Queries、Fortunes、Database Updates、Plaintext 均标注为 N/A。不过实际配置文件(见下文 benchmark_config.json 与 config.toml)同时声明了 plaintext_url = "/plaintext",说明该实现实际上同时支持 JSON 与 Plaintext 两类无数据库测试。
测试变体:default 与 nginx-uwsgi
benchmark_config.json 定义了同一目录下的两个测试入口:
| 字段 | default(uwsgi) | nginx-uwsgi |
|---|---|---|
| json_url | /json |
/json |
| plaintext_url | /plaintext |
/plaintext |
| port | 8080 | 8080 |
| approach | Stripped(剥离型) | Stripped(剥离型) |
| classification | Platform | Platform |
| database | None | None |
| framework | None | None |
| language | Python | Python |
| flavor | Python3 | Python3 |
| orm | Raw | Raw |
| webserver | uWSGI | nginx-uWSGI |
两个变体的 webserver 字段分别标记为 uWSGI 与 nginx-uWSGI,反映两种部署形态:前者由 uWSGI 直接对外提供 HTTP 服务,后者由 nginx 作为前端反向代理、经 UNIX 域套接字转发给 uWSGI。目录中还提供了一份等价的 config.toml,以 TFB 新格式重复声明了 urls.json = "/json"、urls.plaintext = "/plaintext" 等元数据。
在 TFB 工具链中,这份配置由 metadata.py 的 parse_config/validate_test 加载与校验:json_url 必须以 / 开头,json_url 长度不得小于 5、plaintext_url 不得小于 10(校验逻辑见 json/json.py 与 plaintext/plaintext.py)。非 default 的变体会被自动命名为 uwsgi-nginx-uwsgi 运行。
应用源码:hello.py 的路由与响应实现
hello.py 是一个纯 WSGI 应用,不依赖任何 Web 框架,只通过 PATH_INFO 分发请求。其核心实现如下:
import os, sys, time
from email.utils import formatdate
try:
from ujson import dumps as jsonify
except:
from json import dumps as jsonify
def application(environ, start_response):
path = environ["PATH_INFO"]
headers = [ ('Server', 'uWSGI') ]
curr_time = int(time.time())
if curr_time != g_time:
g_time = curr_time
g_asctime = formatdate(timeval=None, localtime=False, usegmt=True)
headers.append( ('Date', g_asctime ) )
if path == '/plaintext':
data = b'Hello, World!'
headers.append( ('Content-Type', 'text/plain') )
headers.append( ('Content-Length', str(len(data))) )
start_response('200 OK', headers)
return [ data ]
if path == '/json':
data = jsonify( {"message": "Hello, World!"} ).encode('utf8')
headers.append( ('Content-Type', 'application/json') )
headers.append( ('Content-Length', str(len(data))) )
start_response('200 OK', headers)
return [ data ]
headers.append( ('Content-Length', '0') )
start_response('400 Bad Request', headers)
return [ b'' ]
这段代码有几个值得注意的工程细节:
- JSON 序列化双保险:优先导入
ujson(快速 C 扩展实现,requirements.txt 固定版本ujson==5.4.0),导入失败时回退到标准库json。这保证了容器在不安装 ujson 时仍可运行,同时尽可能压低序列化开销。 - Date 头按秒缓存:
formatdate只在当前时间秒级变化时才重新生成,避免每个请求都执行日期格式化,减少不必要的 CPU 消耗。 - 响应头逐项手工构造:
Server、Date、Content-Type、Content-Length全部显式给出,与 TFB 的响应头验证规则(见下文)一一对应。 - 未知路径返回 400:非
/json、/plaintext的路径返回空 body 的400 Bad Request。
json 测试的期望响应体是 {"message": "Hello, World!"},plaintext 测试的期望响应体是 Hello, World!。TFB 验证时大小写不敏感,并会警告多余的字节与多余的 JSON 键值对(见 verifications.py 的 verify_helloworld_object)。
部署形态一:uWSGI 直连(default)
uwsgi.dockerfile 构建 uWSGI 直连形态的容器:
FROM python:3.9-bullseye
RUN apt-get update -yqq
RUN apt-get install python3-dev -y
WORKDIR /uw
COPY ./ /uw
RUN pip3 install -U pip; pip3 install -r /uw/requirements.txt
EXPOSE 8080
CMD uwsgi --master -L -l 5000 --gevent 1000 --http :8080 --http-keepalive \
--http-processes $(nproc) -p $(nproc) -w hello \
--add-header "Connection: keep-alive" --pidfile /tmp/uwsgi.pid
启动参数逐项解读:
--master:启用 uWSGI master 进程管理模式。-L:禁止请求日志(disable logging),这是性能测试中的常规做法。-l 5000:设置监听队列深度为 5000。--gevent 1000:启用 gevent 异步模式并设置 1000 个异步并发能力;requirements.txt 中固定了gevent==23.9.1。--http :8080:由 uWSGI 直接以 HTTP 协议监听 8080 端口(default 变体的webserver就是 uWSGI 自身)。--http-keepalive:允许 HTTP Keep-Alive,配合--add-header "Connection: keep-alive"复用 TCP 连接,这是 plaintext 流水线测试(pipeline)能压出高吞吐的前提。--http-processes $(nproc)与-p $(nproc):HTTP 进程数与 worker 进程数均按 CPU 核数动态设置,充分压满多核。-w hello:加载工作目录下的hello.py(其内部定义 WSGI 入口application)。--pidfile /tmp/uwsgi.pid:与 uwsgi.ini 中注释提到的uwsgi_stop.ini配合,用于停止服务。
部署形态二:nginx + uWSGI(nginx-uwsgi)
uwsgi-nginx-uwsgi.dockerfile 构建 nginx 前置的形态:从 nginx 官方 Debian 源安装 nginx,将仓库中的 nginx.conf 复制进容器(并通过 sed 把 uwsgi_params 的 include 路径改为 /etc/nginx/uwsgi_params),随后启动:
CMD nginx -c /uw/nginx.conf && uwsgi --ini uwsgi.ini --processes $(nproc) --gevent 1000 --wsgi hello
这里 uWSGI 不再直接监听 HTTP 端口,而是读取 uwsgi.ini:
[uwsgi]
master
listen = 4096
disable-logging
socket = /var/tmp/uwsgi.sock
chmod-socket = 666
;thunder-lock
pidfile = /var/tmp/uwsgi.pid
关键参数及源码注释中的性能结论:
socket = /var/tmp/uwsgi.sock:使用 UNIX 域套接字 而非 TCP 回环,注释明确说明这是“for performance”。chmod-socket = 666:允许容器内 nginx 进程访问该套接字。listen = 4096:增大监听队列,与内核net.ipv4.tcp_max_syn_backlog、net.core.somaxconn对齐,注释说明这是为 nginx 连入 uWSGI 准备的。disable-logging:关闭请求日志。thunder-lock被注释禁用:注释记载了实测结论——启用 thunder-lock(串行化 accept)时曾导致 Flask 性能下降约 20%,CPU 核无法被压满;而禁用后 bottle 测试约提速 13%,因此“目前保持禁用”。--gevent 1000、--processes $(nproc)与直连形态策略一致,保证多核饱和与异步并发。
nginx 侧配置 nginx.conf 同样围绕性能做了大量取舍:
- 每个 CPU 核一个 worker(注释 "One worker process per core"),
worker_connections 4095依据 nginx error log 提示调大,并开启multi_accept on。 access_log off关闭访问日志;sendfile on、tcp_nopush on优化静态/回传数据路径。keepalive_requests 1000被注释掉:注释指出尽管多复用连接能减少 TCP 建连/断连次数,但可能造成各 worker 连接数不均,故暂不启用;keepalive_timeout 65。listen 8080 default_server deferred reuseport backlog=65535:deferred延迟 accept 以优化 TCP 数据到达,reuseport多核负载均衡,backlog与内核 syn backlog 对齐。location /中uwsgi_pass unix:/var/tmp/uwsgi.sock指向 uWSGI 的 UNIX 套接字,并 include 标准uwsgi_params——这正是 Python README 建议的“用 UNIX 域套接字避免额外 TCP/IP 开销”的落地实现。
TFB 自动化验证:json 与 plaintext 测试类型
uWSGI 的 default 变体在 benchmark_config.json 中声明了 json_url 与 plaintext_url,因此 TFB 工具链会自动为它注册 json 与 plaintext 两类测试。二者的验证逻辑位于 toolset/test_types/json/json.py 与 toolset/test_types/plaintext/plaintext.py,并结合 verifications.py 中的公共校验函数执行。
json 测试的校验点
JsonTestType.verify(json/json.py)按顺序执行:
basic_body_verification:响应非空且必须是合法 JSON(verifications.py)。verify_helloworld_object:将 JSON 键值统一转小写后,必须存在message键且值等于hello, world!;多余键值对、超过 26 字节的冗余内容会产生 warn(verifications.py)。verify_status:要求 HTTP 状态码为 200。verify_headers:要求响应包含Server、Date、Content-Type头,以及Content-Length或Transfer-Encoding;Date必须符合 RFC 822 格式,且间隔 3 秒的两次请求Date不能相同(防缓存);Content-Type必须匹配^application/json(; ?charset=(UTF|utf)-8)?$。
这解释了 hello.py 为什么要手工构造 Server、Date、Content-Length 等头——它们全部是硬性校验项。
plaintext 测试的校验点
PlaintextTestType.verify(plaintext/plaintext.py)要求响应体大小写不敏感地包含 hello, world!,超出必需字节会给出 warn(提示多余字节拖累性能),同样校验状态码 200 与 Content-Type 匹配 ^text/plain(; ?charset=(UTF|utf)-8)?$。
压测脚本
验证通过后,TFB 使用 wrk 发起压测:
- json 使用 toolset/wrk/concurrency.sh:依次执行 Primer(5 秒、8 并发预热)、Warmup(完整时长、最高并发)、随后按
--concurrency-levels(默认[16, 32, 64, 128, 256, 512])逐级加压,每级持续--duration(默认 15 秒),线程数取并发数与nproc的较小值。 - plaintext 使用 toolset/wrk/pipeline.sh 并加载 toolset/wrk/pipeline.lua:
pipeline.lua在 init 阶段用wrk.format()拼接出 16 个请求组成的流水线块(pipeline默认 16),request()每次返回整块,以此测量 HTTP/1.1 管线化吞吐;流水线并发级别默认[256, 1024, 4096, 16384]。这解释了为何两个 Dockerfile 都显式开启 Keep-Alive——plaintext 管线化压测依赖长连接。
验证模式下的整体执行流程
在 TFB 的 verify 模式下,--test uwsgi --mode verify 会触发 framework_test.py 的 verify_urls:对每个注册的测试类型,以 http://<server_host>:8080<url> 为基准 URL 调用上述 verify 逻辑,并将 pass/warn/fail 写入 results/<name>/<test_type>/verification.txt。任一项失败都会让该框架测试整体失败(test.failed)。完整模式(benchmark)下则由 benchmarker.py 在验证通过后调用 wrk 压测并采集容器资源统计。
运行方式与前提条件
在仓库根目录使用 tfb 入口或 python3 toolset/run-tests.py 运行本测试:
# 仅验证 uWSGI 两个变体的 URL 正确性
python3 toolset/run-tests.py --test uwsgi --mode verify
# 完整基准测试(build 镜像、验证、wrk 压测)
python3 toolset/run-tests.py --test uwsgi --mode benchmark --duration 15
前提条件:需要本机具备 Docker 环境,且 FWROOT 环境变量指向仓库根目录(benchmark_config.py 依据它定位 frameworks、toolset 等路径)。uWSGI 测试不启动任何数据库容器(database = "None",见 benchmarker.py 的数据库启动分支),因此部署最简单:直接构建对应 Dockerfile 并在 8080 端口对外服务。
两个变体各自对应独立的镜像与启动命令:
default(uwsgi):uwsgi.dockerfile,uWSGI 以--http :8080直接对外;nginx-uwsgi:uwsgi-nginx-uwsgi.dockerfile,nginx 监听 8080,经/var/tmp/uwsgi.sock转发给 uWSGI。
总结
uWSGI 基准测试是 TFB 中一个极具代表性的“平台级、零依赖”样例:它以纯 WSGI 应用 hello.py 同时支撑 JSON 与 Plaintext 两类测试,通过 uwsgi.ini 与 nginx.conf 中逐行注释的性能取舍(UNIX 套接字、禁用日志、延迟 accept、keepalive 策略、被实测否定的 thunder-lock)展示了 uWSGI 部署的调优思路,并经 benchmark_config.json 声明两种 webserver 形态,接受 TFB 工具链的严格响应头/响应体验证与 wrk 分级压测。无论是想要理解 uWSGI 与 nginx 的组合部署,还是希望参照其“零框架、手写 WSGI”的方式评估服务器本身的能力,这个测试目录都是一份可以逐文件对照学习的完整素材。