1. 前言
Python Package,在实际项目中应用广泛,包含Public Package和Private Package。它有助于我们对代码进行功能封装,使得软件更加结构化、有序化、层次化。主要有几个应用场景:
- 微服务架构下,底层的Core Module,例如
- notification_client,可以支持多种通知方式,方便快捷
- passport_client,大部分portal服务需要的认证client,一改全改,便于维护
- payment_client,封装对多种支付方式的支持,例如alipay、wechat等,基本不变动
- Saas的Python SDK,pip install后即可使用
2. 如何打包Python Package
2.1. Creating the package files
/packaging_tutorial
/example_pkg
__init__.py
setup.py
LICENSE
README.md
setup.py,
version
字段存储package的版本号,每次发布,需要手动递增setup.py,
name
字段就是package的name,需要保证pypi全局唯一参考官方demo
https://packaging.python.org/tutorials/packaging-projects/#uploading-your-project-to-pypi
2.2. Generating distribution archives
- make sure you have the latest versions of setuptools and wheel installed
$ python3 -m pip install --user --upgrade setuptools wheel
- run this command from the same directory where setup.py is located, and will generate two files in the dist directory
$ python3 setup.py sdist bdist_wheel
$ tree dist/
dist/
├── example_pkg_shuzhang-0.0.1-py3-none-any.whl
├── example-pkg-shuzhang-0.0.1.tar.gz
├── example_pkg_shuzhang-0.0.2-py3-none-any.whl
└── example-pkg-shuzhang-0.0.2.tar.gz
0 directories, 4 files
2.3. Uploading the distribution archives
- install twine for uploading the packages
$ python3 -m pip install --user --upgrade twine
- run Twine to upload all of the archives under dist, 3 examples as below
$ python3 -m twine upload --repository-url https://upload.pypi.org/legacy/ dist/*
$ python3 -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*
$ twine upload dist/*
2.4. Just do some tests
- install package using pip
$ python3 -m pip install --index-url https://test.pypi.org/simple/
$ pip install package-name==0.0.2
- just enjoy it
>>> import example_pkg
>>> example_pkg.name
'example_pkg'
3. Reference
New Packaging Python Projects
https://packaging.python.org/tutorials/packaging-projects/Old Python Packaging
https://python-packaging.readthedocs.io/en/latest/minimal.html#picking-a-namepypi
https://pypi.org