Per-request cache in Django?

前端 未结 7 1333
余生分开走
余生分开走 2020-12-08 11:39

I would like to implement a decorator that provides per-request caching to any method, not just views. Here is an example use case.

I have a custom ta

7条回答
  •  爱一瞬间的悲伤
    2020-12-08 12:18

    I came up with a hack for caching things straight into the request object (instead of using the standard cache, which will be tied to memcached, file, database, etc.)

    # get the request object's dictionary (rather one of its methods' dictionary)
    mycache = request.get_host.__dict__
    
    # check whether we already have our value cached and return it
    if mycache.get( 'c_category', False ):
        return mycache['c_category']
    else:
        # get some object from the database (a category object in this case)
        c = Category.objects.get( id = cid )
    
        # cache the database object into a new key in the request object
        mycache['c_category'] = c
    
        return c
    

    So, basically I am just storing the cached value (category object in this case) under a new key 'c_category' in the dictionary of the request. Or to be more precise, because we can't just create a key on the request object, I am adding the key to one of the methods of the request object - get_host().

    Georgy.

提交回复
热议问题