import md5 from django.conf import settings def safe_cache_key(value): '''Returns an md5 hexdigest of value if len(value) > 250. Replaces invalid memcache control characters with an underscore. Also adds the CACHE_MIDDLEWARE_KEY_PREFIX to your keys automatically. ''' for char in value: if ord(char) < 33: value = value.replace(char, '_') value = "%s_%s" % (settings.CACHE_MIDDLEWARE_KEY_PREFIX, value) if len(value) <= 250: return value return md5.new(value).hexdigest()