1. 引言
上一篇文章中,我们详细介绍了如何通过 nexus3 搭建一个 maven 私服。 详解通过 Nexus3.x 搭建 Maven 私服 本文我们来介绍如何通过 nexus3 来搭建一个 python 的 pypi 私服。
2. nexus 配置
打开 nexus。

登录管理员账户,创建仓库。

我们仍然是有三个选择:

他们的区别是:
- proxy — 远程仓库的代理,当用户向这个仓库请求一个 artifact,他会先在本地查找,如果找不到的话,就会从远程仓库下载,然后返回给用户
- hosted — 宿主仓库,用户可以 deploy 到 hosted 中,也可以手工上传构件到 hosted 里,在 central repository 是获取不到的,就需要手工上传到hosted里
- group — 仓库组,将上述多个仓库聚合,对用户暴露统一的地址
那么接下来,我们创建一个 hosted 仓库和一个 group 仓库,创建页面配置很简单,这里不赘述了。

3. 上传 python 包
3.1. 编写代码
执行:
mkdir helloworld touch helloworld/ init .py vim helloworld/demo.py
代码非常简单,一个类中包含一个静态方法用于输出 helloworld:
class Demo:
@staticmethod
def hello():
print('helloworld')
3.2. 编写 setup.py
我们创建 setup.py。
# coding=utf-8
from setuptools import setup
setup(
name='helloworld',
version='1.0',
author="techlog",
license="MIT",
packages=[
'helloworld'
install_requires=[
classifiers=[
"Topic :: Utilities",
"Topic :: Internet",
"Topic :: Software Development :: Libraries :: Python Modules"
具体的 setup.py 的编写规范可以参考:
https://packaging.python.org/tutorials/distributing-packages/#setup-py目录结构 
3.3. 打包
执行:
python setup.py sdist bdist_wheel
此时目录中新增了很多新的文件:

dist 目录下就是我们需要上传的文件。
3.4. 上传
我们使用 twine 包来上传到私服,官网地址:
https://pypi.org/project/twine/
pip install twine
twine upload —repository-url <url> dist/*
<url> 需要替换成我们刚刚搭建的 nexus hosted 私服的 url,在 nexus components 页面有 copy 按钮,点击复制即可。
根据提示填写具有管理员权限的用户名、密码即可。
页面上就可以看到已经上传成功的 pypi 包了。

4. pypi 包的下载和安装
需要安装和下载 pypi 包的话,只需要执行:
pip install helloworld -i <url>/simple —trusted-host <host>
这里 <url> 需要替换成我们刚刚搭建的 nexus group 私服的 url,可以看到安装顺利进行:

5. 调用
编写代码:
from helloworld.demo import Demo
if __name__ == '__main__':
Demo.hello()
执行代码,打印出了:
helloworld
6. 参考资料
https://pypi.org/project/twine/