我已经将一堆用户及其数据导入到django项目中。我需要为每个分配一个密码。这样的代码片段是否可以应付Django哈希和盐?
Answers:
您还可以使用内置函数make_random_password
for user in new_users:
password = User.objects.make_random_password()
user.set_password(password)
# email/print password
make_random_password()
接受关键字参数length
和allowed_chars
。
user.save()
应用更改丢失
你也可以使用from django.utils.crypto import get_random_string
出auth
模块,它接受关键字参数length
,并allowed_chars
为好。
User.objects.make_random_password()
如果已继承,则会给出错误信息。
如果您只需要Django的解决方案,请尝试以下步骤:
要生成普通密码,请尝试使用BaseUserManager。
In [341]: from django.contrib.auth.base_user import BaseUserManager
# simple password, it length is 10, and it contains ascii letters and digits
In [344]: BaseUserManager().make_random_password()
Out[344]: 'aYMX5Wk7Cu'
In [345]: BaseUserManager().make_random_password()
Out[345]: 'rM7759hw96'
In [346]: BaseUserManager().make_random_password()
Out[346]: 'EkbZxEXyAm'
# passed length of a password
In [347]: BaseUserManager().make_random_password(45)
Out[347]: 'dtM9vhSBL9WSFeEdPqj8jVPMH9ytsjPXrkaHUNUQu4zVH'
In [348]: BaseUserManager().make_random_password(45)
Out[348]: 'jypVaXuw9Uw8mD4CXtEhtj2E4DVYx23YTMwy8jGTKsreR'
# passed length of a password and symbols for choice
In [349]: BaseUserManager().make_random_password(45, 'abcdf')
Out[349]: 'daacbfabfccfdbdddbbcddcfcfbfcdabbaccbfcadbccd'
In [351]: import string
# password contains only digits
In [352]: BaseUserManager().make_random_password(50, string.digits)
Out[352]: '00526693878168774026398080457185060971935025500935'
# password contains only ascii symbols in lowercase
In [353]: BaseUserManager().make_random_password(50, string.ascii_lowercase)
Out[353]: 'nvftisuezofnashdhlalfmscnmqtvigwjpfwsyycsefekytmar'
# password contains only ascii symbols in uppercase
In [354]: BaseUserManager().make_random_password(50, string.ascii_uppercase)
Out[354]: 'APKSUHHHTAAJCFEUONIXWWAKJGXIBHTQDZBTSYFTPDFOSRYEQR'
如果您需要强而有力的密码,请尝试在Django中内置“ hashers”
In [355]: from django.contrib.auth.hashers import make_password
In [357]: make_password('')
Out[357]: 'pbkdf2_sha256$30000$JuKXdW3shCjL$PsPJX7Zale5JUBkWpIJI/+QlsuVWhz9Q+GQWVtTpQ/Y='
In [358]: make_password('text')
Out[358]: 'pbkdf2_sha256$30000$lSv8kQ39BHE7$KQC5hRhuphYBXmBrXZBJGC+nxygfNWTDf8zQf/NNgY8='
In [360]: make_password('text', salt=['simething'])
Out[360]: "pbkdf2_sha256$30000$['simething']$D+1vJQx9W2/c9sIz/J+7iEz4d4KFPg/R+0S87n/RKR4="
In [361]: make_password('text', salt=['something'])
Out[361]: "pbkdf2_sha256$30000$['something']$NIcmOkEyg6mnH5Ljt+KvI2LVgZWg6sXS6Rh865rbhSc="
笔记:
只需使用API-django.contrib.auth.models.User
有一个.set_password()
方法。这是一个示例(我还没有测试过,但是您应该了解一下):
from random import choice
from string import digits, letters
from django.contrib.auth.models import User
def _pw(length=6):
s = ''
for i in range(length):
s += random.choice(digits + letters)
return s
for user in User.objects.all(): # or .filter(...)
user.set_password(_pw())
user.save()
.set_password()
helper函数,该User
对象使用您选择的密钥派生函数处理提供的密码并设置.password
字段/属性。