Per-request cache in Django?

前端 未结 7 1313
余生分开走
余生分开走 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:28

    This one uses a python dict as the cache (not the django's cache), and is dead simple and lightweight.

    • Whenever the thread is destroyed, it's cache will be too automatically.
    • Does not require any middleware, and the content is not pickled and depickled on every access, which is faster.
    • Tested and works with gevent's monkeypatching.

    The same can be probably implemented with threadlocal storage. I am not aware of any downsides of this approach, feel free to add them in the comments.

    from threading import currentThread
    import weakref
    
    _request_cache = weakref.WeakKeyDictionary()
    
    def get_request_cache():
        return _request_cache.setdefault(currentThread(), {})
    
    0 讨论(0)
提交回复
热议问题