通过django提高python 编码(二)

通过django来学习常用代码块。

下面方法来之django/conf/init.py

  • 将配置文件导入并作为类的属性
from django.conf import global_settings

class Settings:
    def __init__(self):
        for setting in dir(global_settings):
            if setting.isupper():
                setattr(self, setting, getattr(global_settings,setting))
s = Settings()
print(dir(s))
  • 修改不可变类型变量
class SettingsReference(str):
    def __new__(self, value, setting_name):
        return str.__new__(self, value)

    def __init__(self, value, setting_name):
        self.setting_name = setting_name
s = SettingReference('value', 'name')
print(s)   # name
print(s.setting_name)  # value

下面方法来之django/middleware/csrf.py

  • 生成随机32位字符串,生成64位加盐token, 从token解密为secret

python3.6 提供的secrets 模块具有以下类似的功能

import string
import time
import random
import hashlib

try:
    random = random.SystemRandom()
    using_sysrandom = True
except NotImplementedError:
    import warnings
    warnings.warn('A secure pseudo-random number generator is not available '
                  'on your system. Falling back to Mersenne Twister.')
    using_sysrandom = False

CSRF_ALLOWED_CHARS = string.ascii_letters + string.digits
CSRF_SECRET_LENGTH = 32
CSRF_TOKEN_LENGTH = 2 * CSRF_SECRET_LENGTH

SECRET_KEY = 'zw!p(#x*@d_$+m53*&%(h)x%&+-(p!is5g1^%py3()id#@tlyc'

def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Return 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
    系统生成随机数,时间戳,SECRET_KEY
    """
    if not using_sysrandom:
        random.seed(
            hashlib.sha256(
                ('%s%s%s' % (random.getstate(), time.time(), SECRET_KEY)).encode()
            ).digest()
        )
    return ''.join(random.choice(allowed_chars) for i in range(length))


def _get_new_csrf_string():
    """生成32为秘钥"""
    return get_random_string(CSRF_SECRET_LENGTH, allowed_chars=CSRF_ALLOWED_CHARS)

def _salt_cipher_secret(secret):
    """
    Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
    token by adding a salt and using it to encrypt the secret.
    加盐生成64token
    """
    salt = _get_new_csrf_string()
    chars = CSRF_ALLOWED_CHARS
    pairs = zip((chars.index(x) for x in secret), (chars.index(x) for x in salt))
    cipher = ''.join(chars[(x + y) % len(chars)] for x, y in pairs)
    return salt + cipher
def _unsalt_cipher_token(token):
    """
    Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
    CSRF_TOKEN_LENGTH, and that its first half is a salt), use it to decrypt
    the second half to produce the original secret.
    从token 解密secret
    """
    salt = token[:CSRF_SECRET_LENGTH]
    token = token[CSRF_SECRET_LENGTH:]
    chars = CSRF_ALLOWED_CHARS
    pairs = zip((chars.index(x) for x in token), (chars.index(x) for x in salt))
    secret = ''.join(chars[x - y] for x, y in pairs)  # Note negative values are ok
    return secret
  • 比较两个秘钥相等
# 使用此方法,可以防止时序攻击,时序攻击属于侧信道攻击/旁路攻击
import hmac
def constant_time_compare(val1, val2):
    """Return True if the two strings are equal, False otherwise."""
    return hmac.compare_digest(force_bytes(val1), force_bytes(val2))

你可能感兴趣的:(通过django提高python 编码(二))