简介
peotry可以进行依赖管理(支持锁定版本)、虚拟环境管理,可以处理复杂的依赖关系和版本冲突,简化构建和发布。
相对pip的优势:能解决版本冲突,移除某个组件会把相关依赖都移除,pip只会移除本身,导致后续包冲突可能性较大。
安装
为了避免peotry需要的依赖跟你的项目冲突,通常我们使用pipx安装peotry,pipx会为安装的每个工具单独创建一个虚拟环境,把工具对应的二进制可执行文件放入到PATH中。
安装pipx
# windows install pipx, doc: https://pipx.pypa.io/stable/installation/
pip install --user pipx
# 环境变量添加pipx管理的工具(%USERPROFILE%\.local\bin和<USER folder>\AppData\Roaming\Python\Python3x\Scripts)
pipx ensurepath
# ubuntu install pipx
sudo apt update
sudo apt install pipx
pipx ensurepath
sudo pipx ensurepath --global # optional to allow pipx actions in global scope. See "Global installation" section below.
使用pipx安装poetry
# pipx会为每个独立的python工具创建一个单独的虚拟环境,并将工具的可执行文件链接到~/.local/bin/poetry
pipx install poetry
Dockerfile内安装poetry
ENV POETRY_VERSION=1.8.3
RUN pip install --no-cache-dir poetry==${POETRY_VERSION} -i https://mirrors.aliyun.com/pypi/simple
# Configure Poetry
ENV POETRY_CACHE_DIR=/tmp/poetry_cache
ENV POETRY_NO_INTERACTION=1
ENV POETRY_VIRTUALENVS_IN_PROJECT=true
ENV POETRY_VIRTUALENVS_CREATE=true
# Install poetry pypi plugin and config pypi mirror
RUN poetry self add poetry-plugin-pypi-mirror
ENV POETRY_PYPI_MIRROR_URL=https://pypi.tuna.tsinghua.edu.cn/simple
使用
项目基本操作
# 设置在项目中创建虚拟环境
poetry config virtualenvs.in-project true
# 使用poetry创建项目
poetry new my-folder
# 已有初始化项目
poetry init
poetry env list
poetry env info --path
# 添加依赖
poetry add fastapi
# 安装依赖
poetry install
# 移除依赖
poetry remove fastapi
配置镜像仓库
镜像仓库可以直接用pip的,配置语法稍微有些不同。
针对项目配置:
# 会修改项目的pyproject.toml文件
poetry source add tuna --priority=primary https://pypi.tuna.tsinghua.edu.cn/simple
poetry lock --no-update
# 安装新的依赖,并更新已安装的依赖项到符合要求的版本
poetry install
# 确保已安装的依赖跟pyproject.toml中声明的一致,会移除不需要的包避免包冲突
poetry install --sync --no-cache --no-root
全局配置
%APPDATA%\pypoetry\config.toml
[[tool.poetry.source]]
name = "ali"
url = "https://mirrors.aliyun.com/pypi/simple/"
priority = "primary"
[repositories.ali]
url = "https://mirrors.aliyun.com/pypi/simple/"
[virtualenvs]
in-project = true
pypi-mirror 插件
提供类似PIP_INDEX_URL的功能
poetry self add poetry-plugin-pypi-mirror
export POETRY_PYPI_MIRROR_URL=https://pypi.tuna.tsinghua.edu.cn/simple
安装开发包
# 添加开发依赖的包
poetry add --dev pytest
# 制作生产镜像时,不安装dev的包
poetry install --no-dev
本地配置
poetry分为项目的个人配置,通过poetry config key value --local添加,会在本地添加一个poetry.toml文件。
当前电脑全局配置,通过poetry config key value添加,存储在%APPDATA%\pypoetry\config.toml文件。
所有的config配置都可以通过环境变量设置,POETRY_key=value,key单词之间用_分隔,全部转大写。
export POETRY_VIRTUALENVS_CREATE=true
export POETRY_VIRTUALENVS_IN_PROJECT=true
export POETRY_NO_INTERACTION=1
export POETRY_CACHE_DIR=/tmp/poetry_cache
poetry config virtualenvs.create true --local
poetry config virtualenvs.in-project true --local