Login

Clean-ish memcached key generation

Author:
iiie
Posted:
September 17, 2012
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

Based on snippet #1212 along with it's comments.

Replaced the for loop with translate.

example usage:

from django.core.cache import cache
from mysnippet import cache_key_clean

expensive_func = lambda x: 'x{0}x'.format(x)

input_string = "I wanted a nice value."
key = cache_key_clean(input_string)
result = cache.get(key)
if result is None:
    result = expensive_func(input_string)
    cache.set(key, result)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from django.utils.hashcompat import md5_constructor

drop_chars = ''.join(['%c' % c for c in range(32)]) + ' '

def cache_key_clean(value):
    """
    Make a key of the first up to 228 valid characters of the value,
    appended with the md5 of the whole value.
    """
    md5_hash = md5_constructor(value).hexdigest()
    return ''.join([value.translate(None,drop_chars)[:228], md5_hash])

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.