PyPi 使用 API 令牌进行身份验证

像往常一样使用 twine upload 命令将 Python 项目上传到 PyPi 上,意外地遇到了 401 错误:

WARNING  Error during upload. Retry with the --verbose option for more details.
ERROR    HTTPError: 401 Unauthorized from https://upload.pypi.org/legacy/
         User fournoas has two factor auth enabled, an API Token or Trusted Publisher must be used to upload in place of password.

应该是 PyPi 调整了安全策略,不再允许启用两步验证的账号使用用户名密码来上传项目了,必须使用 API 令牌来进行身份验证。

登录 PyPi ,进入账户设置页,点击「添加 API 令牌」按钮创建 API 令牌。然后修改 ~/.pypirc 配置文件, 用户名字段改为 __token__ ,密码字段改为刚才创建的令牌:

INI[pypi]
username = __token__
password = pypi-**********************************************************

再次运行 twine upload 命令,上传成功。