基于uv 进行类似cargo 的workspace 管理
uv 支持类似cargo workspace模式的项目管理,可以实现多模块的开发机制,以下是一个简单学习
准备
uv 对于workspac 的支持,使用上类似rust cargo
- 项目结构
├── README.md
├── packages
│ ├── api
│ │ ├── README.md
│ │ ├── api
│ │ │ └── __init__.py
│ │ └── pyproject.toml
│ ├── common
│ │ ├── README.md
│ │ ├── pyproject.toml
│ │ └── src
│ │ └── common
│ │ └── __init__.py
│ └── login
│ ├── README.md
│ ├── pyproject.toml
│ └── src
│ └── login
│ └── __init__.py
├── pyproject.toml
├── src
│ └── restapi
│ └── hello.py
- 简单说明
src/restapi 是项目的入口,同时需要包含一个pyproject.toml,里边包含workspace 的配置packages 中的是每个子package 信息
root pyproject.toml
[project]
name = "restapi"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.11"
# 定义依赖
dependencies = [
"login",
"api",
"common",
"tqdm>=4,<5",
]
# 此处定义依赖是workspace
[tool.uv.sources]
login = { workspace = true }
api = { workspace = true }
common = { workspace = true }
[tool.hatch.build.targets.wheel]
packages = ["src/restapi"]
[tool.uv.workspace]
members = ["packages/*", "login"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
packages 一些子包的内容
每个子包应该包含build-system,否则通过uv sync 的时候子包就不知道如何进行构建了(目前的测试)
login 包使用了hatch
[project]
name = "api"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.11"
dependencies = []
[tool.hatch.build.targets.wheel]
packages = ["api"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
common 子包,使用了flit
[project]
name = "common"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.11"
dependencies = []
[build-system]
requires = ["flit_core >=3.2,<4"]
build-backend = "flit_core.buildapi"
root 项目使用
uv 提供了sync 命令可以方便的进行workspace的初始化
- 命令
uv sync -v
- root 使用
from login import login
from api import add
from common import hello
if __name__ == "__main__":
result = login("admin", "admin")
add_result = add(1, 2)
hello_result = hello()
print(result,add_result,hello_result)
启动
uv run src/restapi/hello.py
- 构建包
通过uvx
或者uv tool
uvx --from hatch pyproject-build .
说明
以上是一个简单使用,实际上uv 的workspace 支持对于特定包运行命令 --package 参数
,默认是root,
uv 的workspace 目前使用上还是挺不错的,值得尝试
参考资料
https://docs.astral.sh/uv/concepts/workspaces/
https://docs.astral.sh/uv/getting-started/first-steps/
https://docs.astral.sh/uv/guides/publish/
https://github.com/astral-sh/uv
https://github.com/rongfengliang/uv-workspace-learning