繁体   English   中英

在Django中使用uuid和bcrypt不会生成唯一值

[英]using uuid and bcrypt with django not generating unique values

构建一个uuid然后用bcrypt对其进行哈希处理最终会在每次初始化时在auth_secret中生成一个具有相同值的对象(uuid4()不会为每个新实例生成唯一值)。 这是终端输出

>>> from quickstart.models import FarmUserAuthentication
>>> c = FarmUserAuthentication('as')
>>> d = FarmUserAuthentication('asdfs')
>>> c
<FarmUserAuthentication:  $2a$12$euUMcvhPwPsS7SQgiOVGNeWr792cq.tKONl9bTVjY3nvrxpczPqs6>
>>> d
<FarmUserAuthentication:  $2a$12$euUMcvhPwPsS7SQgiOVGNeWr792cq.tKONl9bTVjY3nvrxpczPqs6>

这是我在models.py中的代码

class FarmUserAuthentication(models.Model):
    auth_id = models.CharField(primary_key = True, max_length = 10)
    hash = bcrypt.hashpw(str(uuid.UUID4()), bcrypt.gensalt())
    auth_secret = models.CharField(max_length=100, default= hash, editable=False)

我相信,通过像在Django模型中看到的那样构造类,您已经在Python中犯了一个基本错误。

这个:

class FarmUserAuthentication(models.Model):
    # ...
    hash = bcrypt.hashpw(str(uuid.UUID4()), bcrypt.gensalt())

是类变量,而不是实例变量 因此,该值在该类的所有实例之间共享。

如果您希望每个实例都有一个唯一值,则通常的方法是使用__init__函数。 但是, 在Django中,您不应覆盖__init__ ,因此您只需在模型中添加一个函数即可创建哈希。 也许是这样的:

class FarmUserAuthentication(models.Model):
    def get_hash():
        return bcrypt.hashpw(str(uuid.UUID4()), bcrypt.gensalt())

或者因为您无法在Django模板中轻松调用事物,也许是一个属性

class FarmUserAuthentication(models.Model):
    @property
    def hash():
        return bcrypt.hashpw(str(uuid.UUID4()), bcrypt.gensalt())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM