I posted some [my-snippet] over at [Django snippets] [django-snippets] the other day.
This code evolved at [work] [ajc] over several months as we encountered a few caching challenges with [memcache] [memcache].
* The first problem was that occasionally some of our cache keys would be too long. Memcache only allows keys up to 250 characters. So the first iteration of this just checked the length and [md5'd] [md5-python] it if it was over the limit.
* Because a lot of our cache keys are based on slugs or titles provided by our staff users, they can occasionally include characters that memcache doesn't like. Zapping the bad characters and replacing them with an underscore solved the problem. The ord(char) < 33 logic was lifted directly from the [memcache Python library] [py-memcache].
* The third problem we had to address came up during our [Django 1.0] [django-10] upgrade. For almost every project, we have the same [application] [gallery-ajc] installed on [several] [gallery-homes] [different] [gallery-access] [sites] [gallery-edge]. As we rolled out the 1.0 code our pre-1.0 cache keys were being accessed by our now-1.0 code and the cached objects weren't unpickling nicely at all in some cases. Hence the automatic addition of the CACHE_MIDDLEWARE_KEY_PREFIX setting. That way we could alter that setting in our 1.0 code and get fresh keys containing 1.0 compatible objects.