1

I'd like to store a value from the database that isn't going to change during a request/response cycle, but gets used hundreds (potentially thousands) of times.

e.g.:

#somefile.py

def get_current_foo(request): # this gets called a lot and is currently a bottleneck
  foo = get_foo_from_db(request.blah)
  return foo

Currently I use memcached to store the value, but this thing gets called enough that even using memcached to store the value is a bottleneck (I'm profiling it as we speak). Is there a way to "cache" the value in-memory for the current request/response cycle?

( follow up from Are python "global" (module) variables thread local? )

3
  • 2
    Can you store it on the request object itself perhaps? Commented Mar 12, 2013 at 15:51
  • I can't think of why not. Thanks! Commented Mar 12, 2013 at 15:52
  • Possible duplicate of Per-request cache in Django? Commented Feb 7, 2016 at 9:09

1 Answer 1

4

If it is per-request data, store it on the request object itself. :-)

See Per-request cache in Django? for some techniques to do so.

Sign up to request clarification or add additional context in comments.

4 Comments

That link seems to address caching the request itself in threadlocals, which solves a different concern (passing the request around everywhere). Since I have the request already, it seems I can just add the attribute to it, and check for it in future calls, simple enough, if i'm understanding correctly.
@BenRoberts: the second answer stores things directly on the Django request; I wasn't 100% certain that you could simply do request.my_cache = cachedvalue and then test for it with getattr(request, 'my_cache', None).
Ah. Got it. I'll try the basic way first and if that doesn't work, I'll go down that route.
Simply setting the attribute (request.myvalue) and using getattr(request, 'myvalue', None) seems to be working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.