如何使用 Maturin 构建并发布 wheel?

解读

在国内 FastAPI 面试中,面试官问“怎么用 Maturin 构建并发布 wheel”,并不是想听你背命令,而是考察三件事:

  1. 你是否知道 FastAPI 的性能瓶颈有时在“纯 Python 计算”上,需要用 Rust 扩展;
  2. 你是否能把 Rust 扩展打包成标准 wheel,避免让用户本地装 Rust 工具链;
  3. 你是否熟悉国内镜像、CI、合规发布(Gitee、腾讯软件源、私有 PyPI)等工程闭环。
    答不出“为什么 FastAPI 项目要用 Maturin”,直接掉分。

知识点

  1. Maturin 定位:零配置打包工具,把 Rust crate 编译成 cp38-cp311 多平台 wheel,同时生成 pyo3 绑定。
  2. 与 setuptools-rust 区别:Maturin 不需要 setup.py,一条命令完成编译、元数据注入、PEP 517 构建。
  3. 国内网络:rustup 换清华源,cargo 换科大或阿里云,manylinux 镜像用 dockerhub 代理或腾讯云 TCR。
  4. 合规发布:
    • 公有 PyPI:先测 test.pypi.org,再发正式源;需要 API Token,禁止明文密码。
    • 私有源:Nexus、Artifactory、DevOps 平台内置 PyPI 服务,需配置 ~/.pypirc 中的 index-server。
  5. FastAPI 集成:把 .so/.pyd 当作普通包导入,uvicorn 启动时无感知;注意多进程 reload 会重复加载 Rust 符号,建议用 --workers 1 调试。
  6. 版本号同步:Cargo.toml 的 version 与 Python version 保持一致,CI 里用 sed 或 git tag 自动替换。
  7. 审计与许可证:Rust 依赖树用 cargo-deny 扫描,GPL 组件不能打包进 wheel;国内大厂对许可证合规一票否决。

答案

步骤以 Linux x86_64 + Python 3.11 为例,Windows 与 macOS 只需换镜像名,命令一致。

  1. 环境准备
    rustup default stable
    rustup target add x86_64-unknown-linux-gnu
    pip install maturin>=1.5
    国内 cargo 换源:mkdir -p ~/.cargo && echo '[source.crates-io]\nreplace-with = "ustc"\n[source.ustc]\nregistry = "https://mirrors.ustc.edu.cn/crates.io-index/"' > ~/.cargo/config

  2. 创建 Rust 扩展
    cargo new --lib fastapi_utils
    修改 Cargo.toml:
    [lib]
    name = "fastapi_utils"
    crate-type = ["cdylib"]
    [dependencies]
    pyo3 = { version = "0.20", features = ["extension-module"] }
    写 src/lib.rs:
    use pyo3::prelude::*;
    #[pyfunction]
    fn fib(n: u64) -> u64 { (2..=n).fold(1, |acc, _| acc + 1) }
    #[pymodule]
    fn fastapi_utils(_py: Python, m: &PyModule) -> PyResult<()> { m.add_function(wrap_pyfunction!(fib, m)?)?; Ok(()) }

  3. 本地构建
    maturin build --release --strip --compatibility manylinux2014
    生成 dist/fastapi_utils-0.1.0-cp311-cp311-manylinux2014_x86_64.whl

  4. 本地验证
    python -m venv venv && source venv/bin/activate
    pip install dist/*.whl
    python -c "from fastapi_utils import fib; print(fib(10))"

  5. 国内 CI 自动发布(以 GitHub Actions + 腾讯 TCR 镜像为例)
    name: BuildWheel
    on: push: tags: 'v*'
    jobs:
    linux:
    runs-on: ubuntu-latest
    container:
    image: ccr.ccs.tencentyun.com/pypi/manylinux2014_x86_64:rust1.70
    steps:
    - uses: actions/checkout@v4
    - run: pip install maturin
    - run: maturin build --release --compatibility manylinux2014
    - run: pip install twine
    - run: twine upload --repository-url https://pypi.douban.com/simple/ -u token -p ${{ secrets.PYPI_API_TOKEN }} dist/*

  6. 国内私有源上传
    配置 ~/.pypirc:
    [distutils]\nindex-servers = private\n[private]\nrepository = https://nexus.xxx.com/repository/pypi-hosted/\nusername = deploy-token\npassword = ${NEXUS_PASSWORD}
    然后 twine upload --repository private dist/*

  7. FastAPI 项目使用
    from fastapi import FastAPI
    from fastapi_utils import fib
    app = FastAPI()
    @app.get("/fib/{n}")
    def read_fib(n: int):
    return {"result": fib(n)}
    启动:uvicorn main:app --workers 4

拓展思考

  1. 交叉编译:国内 ARM 服务器占比高,可用 cargo-zigbuild 在 x86 CI 上交叉出 aarch64-unknown-linux-gnu 的 wheel,再通过 QEMU 测试。
  2. 增量编译:把 target 目录缓存到腾讯 COS 或阿里云 OSS,减少 CI 时间 70%。
  3. ABI 兼容:如果扩展只用 PyO3 的 abi3 特性,可打出 cp38-abi3-linux_x86_64.whl,一次构建,通杀 3.8-3.12。
  4. 安全加固:使用 cargo-audit 在 CI 阶段阻断高危 CVE;wheel 内嵌 .so 用 strip + upx 压缩,降低 30% 体积。
  5. 线上排障:FastAPI 生产环境开启 opentelemetry-rust,把 Rust 扩展内部 span 透传到 Python 追踪,定位 CPU 热点。