什么是防止memcached CacheKeyWarning的好/结构化方法?

Dav*_*Lam 3 django memcached caching

我想知道是否有人知道一种方便的方法或方法来确保你传递的钥匙django.core.cache.set()或者没问题cache.get().

来自https://docs.djangoproject.com/en/1.3/topics/cache/#cache-key-warnings:

Memcached是最常用的生产缓存后端,它不允许超过250个字符的缓存键或包含空格或控制字符,并且使用此类键会导致异常.

我在md5_constructor()这里找到了这个函数:https://github.com/django/django/blob/master/django/utils/hashcompat.py,

也许一种方法是md5-如果你总是使用的钥匙?不确定是否安全.

iMo*_*om0 5

  1. md5_constructorhashlib.md5在标准库,其digest方法可以返回安全密钥适合长度的限制。如果您的原始密钥长度大于 250,您应该使用它或其他人来确保密钥安全。
  2. 对于原键中的每个字符,请确保ord(character) >= 33,如果不是,请用下划线或您喜欢的其他安全字符替换不安全字符。


Ger*_*ano 5

您可能想要使用自定义键功能https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-CACHES-KEY_FUNCTION

在您的设置中进行设置:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'KEY_FUNCTION': 'path.to.my.make_key',
        'LOCATION': [
            '127.0.0.1:11211',
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

我会使用类似的东西:

from django.utils.encoding import smart_str

def _smart_key(key):
    return smart_str(''.join([c for c in key if ord(c) > 32 and ord(c) != 127]))

def make_key(key, key_prefix, version):
    "Truncate all keys to 250 or less and remove control characters"
    return ':'.join([key_prefix, str(version), _smart_key(key)])[:250]
Run Code Online (Sandbox Code Playgroud)