# Create a random SECRET_KEY to put it in the main settings.
options['secret_key'] = get_random_secret_key()
2. django/core/management/utils.py
def get_random_secret_key():
"""
Return a 50 character random string usable as a SECRET_KEY setting value.
"""
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
return get_random_string(50, chars)
3. django/utils/crypto.py
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
"""
if not using_sysrandom:
# This is ugly, and a hack, but it makes things better than
# the alternative of predictability. This re-seeds the PRNG
# using a value that is hard for an attacker to predict, every
# time a random string is required. This may change the
# properties of the chosen random sequence slightly, but this
# is better than absolute predictability.
random.seed(
hashlib.sha256(
("%s%s%s" % (
random.getstate(),
time.time(),
settings.SECRET_KEY)).encode('utf-8')
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))
SECRET_KEY是在startproject时候生成的,最终引用的是上述代码,具体的你可以自己去源码查看。PS 补充一下,以上代码的django版本为
1.10,具体代码执行步骤如下(其它版本也可以按照这个方法来):1. django/core/management/commands/startproject.py
2. django/core/management/utils.py
3. django/utils/crypto.py
网上找到这么一段代码
另一种方式
这个值是django架构自己实现生成的,通过django的源码可以看到这个值的生成方式,该值在你使用startproject开始调用生成。你可以从manage.py为入口慢慢追踪定位到目标所在。
如果要手工生成来替换,可以使用openssl rand -base64 32
32是位数,位数越大,生成的随机数就越长.