python - Django make_password 以编程方式创建大量用户列表太慢

标签 python django django-models

我需要在 Django 中以编程方式创建数百(可能数千)个用户。我正在使用类似的东西:

from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
for username, email, pwd in big_user_list:
    m = User(username=username, email=email, password=make_password(pwd))
    m.save()

执行时间太长。通过在没有密码的情况下运行上述脚本,我已经确认 make_password 是罪魁祸首。

有没有关于这个缓慢问题的,我真的需要这个脚本来快速执行。

最佳答案

您可以使用 django.contrib.auth.hashers.MD5PasswordHasher 作为初始密码。根据 Django docs on how Django stores passwords ,

By default, Django uses the PBKDF2 algorithm with a SHA256 hash, a password stretching mechanism recommended by NIST. This should be sufficient for most users: it’s quite secure, requiring massive amounts of computing time to break.

[...]

Django chooses the an algorithm by consulting the PASSWORD_HASHERS setting. This is a list of hashing algorithm classes that this Django installation supports. The first entry in this list (that is, settings.PASSWORD_HASHERS[0]) will be used [by default] to store passwords, and all the other entries are valid hashers that can be used to check existing passwords. [...]

The default for PASSWORD_HASHERS is:

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher'
)

因此您希望保持现在的默认值,但在开始时使用较弱的散列器;确保 MD5PasswordHasher 出现在列表中。然后使用

make_password(pwd, None, 'md5')

最初生成一个普通的加盐 MD5 密码;如果初始密码足够随机,这不会太弱。随着用户更改密码,他们的密码将使用更强的算法进行加密。

关于python - Django make_password 以编程方式创建大量用户列表太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18273110/

相关文章:

python - 通过将两个长度不等的列表压缩在一起来创建字典

python - Docker容器上的Django MSSQL服务器不会迁移

django - Django:将模型重构为单独的文件后,它们无法被syncDB或south识别

python - 服务大文件的 Django Filewrapper 内存错误,如何流式传输

django - Bootstrap Writing In Columns(像报纸一样)

django-models - 数据库设计 ManyToMany, OneToMany, ManyToOne, Django 模型

database - Django:在嵌套数据结构中序列化模型?

Enthought Canopy 中的 Python 版本不是最前面的

python - 将函数的结果写入 csv 中

python - 在python中用占位符替换字符串