我有一个私人 PyPI 存储库。有什么方法可以在
pip.conf
中存储类似于 .pypirc
的凭据吗?
我的意思是。目前在
.pypirc
你可以有这样的配置:
[distutils]
index-servers = custom
[custom]
repository: https://pypi.example.com
username: johndoe
password: changeme
根据我的发现,你可以输入
pip.conf
:
[global]
index = https://username:[email protected]/pypi
index-url = https://username:[email protected]/simple
cert = /etc/ssl/certs/ca-certificates.crt
但在这里我看到两个问题:
有没有办法在网址之外存储用户名和密码?
理想情况下,您应该配置 Pip 的 keyring 支持。某些后端以加密/受保护的形式存储凭据。包装生态系统的其他部分,例如 Twine,也支持密钥环。
或者,您可以存储 Pip 的凭据以在
~/.netrc
中使用,如下所示:
machine pypi.example.com
login johndoe
password changeme
Pip 将在访问
https://pypi.example.com
时使用这些凭据,但不会记录它们。您必须单独指定索引服务器(例如问题中的pip.conf
)。
请注意,
~/.netrc
必须由pip
执行的用户拥有。它也不能被任何其他用户读取。无效文件将被默默忽略。您可以像这样确保权限正确:
chown $USER ~/.netrc
chmod 0600 ~/.netrc
此权限检查在 Python 3.4 之前不适用,但无论如何它都是一个好主意。
在发出 HTTP 请求时,Pip 在内部使用 requests。 requests 使用标准库 netrc 模块来读取文件,因此字符集仅限于 ASCII 子集。
如何将用户名/密码存储为环境变量,
export username=username
export password=password
并在 pip.conf 中引用它们,如下所示:
[global]
index = https://$username:[email protected]/pypi
index-url = https://$username:[email protected]/simple
cert = /etc/ssl/certs/ca-certificates.crt
我使用 Gitlab CI 的秘密变量来存储凭据。检查您的 CI 工具中是否有等效项。
鉴于 issue 4789 仍然开放,您可以在您的requirements.txt中使用以下方法:
--extra-index-url=https://${PYPI_USERNAME}:${PYPI_PASSWORD}@my.privatepypi.com
private-package==1.2.3
...
如果您尝试在设置了这些环境变量的情况下运行
pip install -r requirements.txt
,您会发现 pip 仍然要求提供凭据。这是因为 pip 并不像人们期望的那样插入表达式 ${PYPI_USERNAME}
,而是对其进行 url 编码。本例中您的用户名和密码表示为 https://%24%7BPYPI_USERNAME%7D:%24%7BPYPI_PASSWORD%[email protected]
这里的工作,我承认应该有更好的方法,但我们可以将 pip 作为脚本运行:
python3 -m pip install -r requirements.txt
来自男人:
-m module-name
Searches sys.path for the named module and runs the corresponding .py file as a script.
我知道它并没有按照它的表述方式回答问题,但也可以使用
keyring
python 模块进行 pip 身份验证:
https://pypi.org/project/keyring/
https://pip.pypa.io/en/stable/topics/authentication/#keyring-support%3E
嘿,你可以简单地 运行 pip install 并将 url 作为参数传递给私有仓库(我正在使用 Artifactory,但这并不重要):
人工示例:
pip install {lib_name} -U -i https://{user_name}:{token_to_prvate_repo}@artifactory.{company_name}.com/api/pypi/pypi/simple
Github 示例:
pip install git+https://${GITHUB_USER}:${GITHUB_TOKEN}@github.com/user/project.git@{version}
Bitbucket 示例:
pip install git+https://${BITBUCKET_USER}:${BITBUCKET_APP_PASSWORD}@bitbucket.org/user/project.git@{version}'
可以从管道/密钥库或其他安全解决方案读取变量。