python - django setting里面SECRET_KEY是怎么生成的

查看:1191
本文介绍了python - django setting里面SECRET_KEY是怎么生成的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

如题,我们在django的setting里面有个
SECRET_KEY = '9b7+8l35&)ldkw%5w)bg_0f=2^+%o9floh8_v)-4k0n)4^98jl'

这个值是通过什么库来生成的

解决方案

In [1]: from django.core.management import utils

In [2]: utils.get_random_secret_key()
Out[2]: '_5*c1zg+tvx(o*+6*e=@*%)7^if8f^c0r^_6ajyqz4at+%j(q='

SECRET_KEY是在startproject时候生成的,最终引用的是上述代码,具体的你可以自己去源码查看。

PS 补充一下,以上代码的django版本为1.10,具体代码执行步骤如下(其它版本也可以按照这个方法来):

1. django/core/management/commands/startproject.py

# 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))

这篇关于python - django setting里面SECRET_KEY是怎么生成的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆