Python项目打包与部署(四):项目依赖管理

本教程其它章节

Python 项目依赖管理

Python编程效率高,其中1个主要原因是有大量开源库,如常见的 requests, pandas, numpy 等。 通常,python 项目严重依赖各类第3方库。 不同项目对同1个库的版本可能有不同要求,稍不注意,项目就无法运行。因此,依赖管理是Python项目管理的重要内容

1、使用 requirements.txt 管理依赖库

pip + requirements.txt 是管理项目依赖的最常见方式。 这种方式,适合于手工部署、离线部署场景。

1) requirements.txt 格式

Django==3.2.8
djangorestframework==3.1.3	
docopt==0.6.2
gnureadline==6.3.3
click

每一行、代表1个依赖库,可以加版本,也可以不加

2) 生成requirements.txt文件

此文件可以手工创建编辑。

如果项目使用单独的虚拟环境开发,可用命令生成 requirements.txt ,自动将当前虚拟环境安装的依赖包写入requirements.txt文件。

pip freeze > ./requirements.txt

3) 根据 requirements.txt 安装依赖

安装项目时,可以根据安装包中的requirements.txt 来安装依赖库:

pip install -r requirements.txt 

-r requirements.txt 指示pip安装requirements.txt 中列出的第3方依赖库。

4) 离线安装依赖

如果安装服务器不能访问internet,按如下步骤安装依赖:

(1)开发服务器端 ,导出并打包依赖包
pip download -d require -r requirements.txt

此命令在当前目录下生成 ./require目录,存放了下载的依赖包,

(2) 打包 require 目录,并复制到安装服务器安装目录。
(3)本地安装依赖

在项目目录执行命令安装:

pip install --no-index --find-links=require -r requirements.txt 

5) 根据源码import 语句生成 requirements.txt

pipreqs 工具,可根据源码中的 import 语句自动生成 requirements.txt 文件

使用 pipreqs 则需要安装

pip install pipreqs

此工具是基于 imports,这是什么意思呢,即项目引入了哪个包,此工具才会把引入的包写到 requirements.txt 中,要比 pip freeze 更准确,

执行 pipreqs --use-local ./ 生成 requirements.txt

注意,此工具不能分析wheel格式的第3方库,故不能发现其使用的依赖,如 django使用的 mysqlclient 不能生成,需要手工添加

几种生成 requirements.txt 文件 方式对比

名称优点缺点
pip freeze包含列表完全不相关的依赖包也会包含进来
pipreqs只会包含项目 imports 的包包含列表不是很完全
pip-compile精准控制项目依赖包需要手动操作,不方便

绝大多数情况下,pip + requirements.txt 就可以满足项目依赖安装部署的需要。

2、使用pyproject.toml管理依赖

如果使用 setuptool 构建工具与包发行服务器来部署项目,则通过pyproject.toml来配置项目依赖来方便

1) pyproject.toml中配置依赖

dependencies 依赖项配置

[project]
dependencies = [
  "httpx",
  "gidgethub[httpx]>4.0.0",
  "django>2.1; os_name != 'nt'",
  "django>2.0; os_name == 'nt'",
]

也可以设置可选依赖项 optional-dependencies, 在安装项目时,指定是否安装

[project.optional-dependencies]
gui = ["PyQt5"]
cli = [
  "rich",
  "click",
]

上例中,使用下面命令安装项目时,指定了gui参数,则会安装 PyQt5 依赖库。
pip install your-project-name[gui]

指定项目最低Python版本


[project]
requires-python = ">= 3.8"

2) 自动安装依赖

当使用 pip install your_project_name 时, 会自动安装配置文件中指定的依赖.

3、使用 Pipenv工具来管理依赖

使用requirements.txt管理依赖时,Python官方推荐使用 Pipenv工具更加方便地管理依赖。

安装 pipenv

python3 -m pip install --user pipenv

使用步骤:

1、在项目目录下安装第3方库。

cd myproject
pipenv install requests

命令运行后,会在项目目录下添加1个 Pipfile文件,用于track 依赖库的版本。

  1. 使用已安装的依赖库

与使用pip安装后,使用方式一致。

import requests

response = requests.get('https://httpbin.org/ip')
print('Your IP is {0}'.format(response.json()['origin']))
  1. 用pipenv运行python文件
pipenv run python main.py

输出 :Your IP is 8.8.8.8

或者使用 pipenv shell 生成pipenv运行环境,每条命令会自动加上 pipenv run,

  1. 生成生产环境

当完成开发后,可以生成生产环境依赖文件Pipfile.lock文件, 这个文本不允许手工编辑。

$ pipenv lock