无法在Python 3.5上安装'secrets' (使用pip,ubuntu 3.5)

11

我正在尝试在Ubuntu 16.04上的Python 3.5中使用库secrets。它没有随着python安装而来,且我无法通过pip进行安装。是否有方法使其在Python 3.5上正常工作?


1
当您尝试使用pip安装它时,您看到了哪些错误? - yentsun
5个回答

15

很烦人的是,这里没有适用于PyPi模块的内容,且Ubuntu使用古老版本的Python,希望有人能修复这个问题。与此同时:

如果您使用旧版本的Python(>=2.4并且<=3.5),您可以使用os库中的urandom函数生成密钥。

例如:

from os import urandom

urandom(16) # same as token_bytes(16)
urandom(16).hex() # same as token_hex(16) (python >=3.5)
为了使某个东西向后兼容,同时在支持时仍使用新的 secrets 库,你可以这样做:
try:
    from secrets import token_hex
except ImportError:
    from os import urandom
    def token_hex(nbytes=None):
        return urandom(nbytes).hex()

值得注意的是,当请求的字节数为“None”时,“urandom()”没有相同的“合理默认”规则。因此,您的向后兼容解决方案需要手动设置“nbytes”为某个“合理默认值”(尽管我不确定有多少人使用此功能)。 - Kyle Willmon

10
你可以使用Python 2.7、3.4和3.5的secrets模块的后向兼容版本,名称为python2-secrets。(在我看来,这个名称有点令人困惑)
安装方法:
pip install --user python2-secrets

简洁的解决方案很可爱。 - Adi Prasetyo

2

您正在尝试使用的模块在Python 3.5版本之前并不是Python的一部分。

看起来在那个版本中,也无法从pip下载secrets模块。

$ pip install secrets
Collecting secrets
 Could not find a version that satisfies the requirement secrets (from versions: ) No matching distribution found for secrets

当您在 Python 3.6 环境下工作时,该模块可以直接导入,因为它是标准库的一部分:

Python 3.6.3 (default, Mar  7 2018, 21:08:21)  [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information.
>>> import secrets
>>> print(secrets)
<module 'secrets' from '/home/mikel/.pyenv/versions/3.6.3/lib/python3.6/secrets.py'>

1
在Python 3.x中,请使用pip install secret代替。

0

如果您查看PEP 506,该提案讨论了如何实现secrets并指向包作者的Bitbucket存储库,该存储库现在是官方Python标准库的一部分!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接