Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7011879
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T22:10:59+00:00 2026-05-27T22:10:59+00:00

I would like to implement a decorator that provides per-request caching to any method,

  • 0

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 tag that determines if
a record in a long list of records is
a “favorite”. In order to check if an
item is a favorite, you have to query
the database. Ideally, you would
perform one query to get all the
favorites, and then just check that
cached list against each record.

One solution is to get all the
favorites in the view, and then pass
that set into the template, and then
into each tag call.

Alternatively, the tag itself could
perform the query itself, but only the
first time it’s called. Then the
results could be cached for subsequent
calls. The upside is that you can use
this tag from any template, on any
view, without alerting the view.

In the existing caching mechanism, you
could just cache the result for 50ms,
and assume that would correlate to the
current request. I want to make that
correlation reliable.

Here is an example of the tag I currently have.

@register.filter()
def is_favorite(record, request):

    if "get_favorites" in request.POST:
        favorites = request.POST["get_favorites"]
    else:

        favorites = get_favorites(request.user)

        post = request.POST.copy()
        post["get_favorites"] = favorites
        request.POST = post

    return record in favorites

Is there a way to get the current request object from Django, w/o passing it around? From a tag, I could just pass in request, which will always exist. But I would like to use this decorator from other functions.

Is there an existing implementation of a per-request cache?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T22:11:00+00:00Added an answer on May 27, 2026 at 10:11 pm

    Using a custom middleware you can get a Django cache instance guaranteed to be cleared for each request.

    This is what I used in a project:

    from threading import currentThread
    from django.core.cache.backends.locmem import LocMemCache
    
    _request_cache = {}
    _installed_middleware = False
    
    def get_request_cache():
        assert _installed_middleware, 'RequestCacheMiddleware not loaded'
        return _request_cache[currentThread()]
    
    # LocMemCache is a threadsafe local memory cache
    class RequestCache(LocMemCache):
        def __init__(self):
            name = 'locmemcache@%i' % hash(currentThread())
            params = dict()
            super(RequestCache, self).__init__(name, params)
    
    class RequestCacheMiddleware(object):
        def __init__(self):
            global _installed_middleware
            _installed_middleware = True
    
        def process_request(self, request):
            cache = _request_cache.get(currentThread()) or RequestCache()
            _request_cache[currentThread()] = cache
    
            cache.clear()
    

    To use the middleware register it in settings.py, e.g:

    MIDDLEWARE_CLASSES = (
        ...
        'myapp.request_cache.RequestCacheMiddleware'
    )
    

    You may then use the cache as follows:

    from myapp.request_cache import get_request_cache
    
    cache = get_request_cache()
    

    Refer to the django low level cache api doc for more information:

    Django Low-Level Cache API

    It should be easy to modify a memoize decorator to use the request cache. Have a look at the Python Decorator Library for a good example of a memoize decorator:

    Python Decorator Library

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to implement a method that can get the svn revision number
I would like to implement something similar to a c# delegate method in PHP.
I would like to implement an interactive evolutionary algorithm for generating music (probably just
I would like to implement a producer/consumer scenario that obeys interfaces that are roughly:
I would like to implement a post build event that performs the following actions
I would like to implement the method User.calculate_hashed_password . I'm trying to use the
We would like to implement a web form that automatically saves content at regular
I would like to implement a method like this: boost::unique_future<int> foo() { return defer([=]
I would like to implement a function that takes as input a size n
I would like to injecte a decorator on a method class from another class.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.