- November 23, 2008
- memcache cache caching
- 2 (after 2 ratings)
If any cache keys you generate include user (staff or public) supplied data, they may: be too long, contain invalid characters (at least by memcache's standards), or both.
This helper will sub out any invalid characters and md5 the key if it's too long.
Additionally, it'll insert the CACHE_MIDDLEWARE_KEY_PREFIX from django.conf.settings for you. In your memcache instances are used by multiple applications (Django or otherwise) this can help ensure your keys are unique to that a particular app on a particular site.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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()
More like this
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 6 months, 1 week ago
- Crispy Form by sourabhsinha396 7 months ago
- ReadOnlySelect by mkoistinen 7 months, 2 weeks ago
- Verify events sent to your webhook endpoints by santos22 8 months, 1 week ago
- Django Language Middleware by agusmakmun 8 months, 3 weeks ago