Login

get_cache_or_query - Shortcut to common cache signature

Author:
menendez
Posted:
May 5, 2008
Language:
Python
Version:
.96
Score:
6 (after 6 ratings)

Replaces something like this: cache_key = 'game1' the_game = cache.get(cache_key) if not the_game: the_game = Game.objects.get(id=1) cache.set(cache_key, the_game, 60245)

With this: the_game = get_cache_or_query('game1', Game, seconds_to_cache=60245, id=1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def get_cache_or_query(cache_key, model, seconds_to_cache=900, **kwargs):
    '''
        Based on concept by Rudy Menendez.
        Gets the query from cache or returns the orm.
        
        Example: the_game = get_cache_or_query('game1', Game,
                            seconds_to_cache=60*24*5, id=1) # 5 day timeout
    '''
    from django.core.cache import cache
    
    q = cache.get(cache_key)
    if not q:
        q = model.objects.get(**kwargs)
        cache.set(cache_key, q, seconds_to_cache)
    return q

More like this

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

Comments

Please login first before commenting.