Django memcache cache cache templates

I have a large Django project with several related projects and lots of caching. Currently, it has a file that stores auxiliary cache functions. So, for example, get_object_x (id) will check the cache for this object, and if it was not there, go to the database and pull it out and return it, caching it along the way. The same template is used to cache groups of objects, and the file is also used for invalidation methods.

However, the problem is related to import between applications. The application model file has a number of helper functions for which we want to use the cache, and the cache_helpers file should obviously import the model file.

So my question is: what is the best way to do this so as not to subject the code to cyclical import issues (or maybe a more sensible way at all)? Ideally, we could make invalidation a better, less manual way. I guess using Django custom managers and signals is the best place to start, getting rid of the cache_helpers file in general, but does anyone have any better suggestions or directions on where to look?

+4
source share
2 answers

The general Python pattern for preventing round-robin imports is to put one set of imports inside dependent functions:

# module_a.py import module_b def foo(): return "bar" def bar(): return module_b.baz() # module_b.py def baz(): import module_a return module_a.foo() 

As for caching, it looks like you need a function that looks something like this:

 def get_cached(model, **kwargs): timeout = kwargs.pop('timeout', 60 * 60) key = '%s:%s' % (model, kwargs) result = cache.get(key) if result is None: result = model.objects.get(**kwargs) cache.set(key, result, timeout) return result 

Now you do not need to create "getbyid" methods for each of your models. You can do this instead:

 blog_entry = get_cached(BlogEntry, pk = 4) 

You can write similar functions to work with full QuerySets instead of individual model objects using the .get () method.

+7
source

Since you indicated that you are caching instances of the Django ORM model, take a look at django-orm-cache , which provides automatic caching of model instances and is reasonable about when to invalidate the cache.

Your round-robin import won't be a problem - all you have to do is expand the models that need to be cached from the ormcache.models.CachedModel class instead of Django django.db.models.Model and you will get the caching "for free".

+3
source

All Articles