发布Python包到pypi

官方文档

打包 Python 项目

开始

创建项目

上一篇文章的代码为例

目录结构如下

src 存放代码的目录
	scrapy-redis-bf 需要上传的包
tests/ 存放一些测试文件,可以为空
LICENSE 开源许可证
pyproject.toml 项目设置
README.md 

其中主要关心的是pyproject.toml, 许可证的话在https://choosealicense.com/随便弄一个就行

build-system

首先需要选择构建工具,官方列出了四种:hatchling、setuptools、Flit和PDM

hatchling

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

setuptools

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

选择哪一种就将配置写入pyproject.toml,任意一种都可以

pyproject.toml

填写一些包的信息

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "scrapy-redis-bf"
version = "0.0.8"
authors = [
  { name="kanade", email="[email protected]" },
]
description = "scrapy_redis use bloomfilter"
readme = "README.md"
license = { file = "LICENSE" }
requires-python = ">=3.7"
classifiers = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
]
dependencies = [
    "scrapy-redis >= 0.6.8",
]

[project.urls]
"Homepage" = "https://github.com/kanadeblisst/scrapy_redis_bf"
"Bug Tracker" = "https://github.com/kanadeblisst/scrapy_redis_bf/issues"

其他的一看应该就知道了,dependencies是你上传的包需要安装的依赖

接着改下README.md然后就可以开始构建了

构建whl

先安装:pip install build

然后再pyproject.toml所在目录运行 python -m build接着会生成两个文件到dist目录下,其中的whl文件就可以直接用pip安装了

创建pypi账号

有两个网站:https://test.pypi.orghttps://pypi.org ,前者大概是用来测试用的

这里以前者为例,打开网站,注册账号->验证邮箱->创建API tokens

https://pypi.org/manage/account/一直滑到Add API token 填写一个名字,然后选择scope点Add token,会得到一个以pypi-开头的字符串,就是token

接着在用户目录创建.pypirc文件,比如Windows就在:C:\Users\Administrator下创建,Administrator是登陆的用户名。内容如下,修改下token到password后面即可。注意: pypi和testpypi两个网站的账号和token都是不一样的

[distutils]
index-servers =
    pypi
    testpypi

[pypi]
repository = https://upload.pypi.org/legacy/
username = __token__
password = pypi-xxxxx

[testpypi]
repository = https://test.pypi.org/legacy/
username = __token__
password = pypi-xxxxx
上传到pypi

安装包:pip install twine

上传: twine upload --repository testpypi dist/* 这里的testpypi就是上面.pypirc文件里的,也可以写pypi

上传的时候可能会出现网络错误,需要先设置的国外的代理,命令行执行:set HTTPS_PROXY=127.0.0.1:10809

安装包

testpypi: pip install --index-url https://test.pypi.org/simple/ scrapy-redis-bf
pypi: pip install --index-url https://pypi.org/simple/ scrapy-redis-bf

如果是其他源的话,估计同步过去得要点时间

猜你喜欢

转载自blog.csdn.net/Qwertyuiop2016/article/details/127110359