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? )

Community
  • 1
  • 1
B Robster
  • 40,605
  • 21
  • 89
  • 122

1 Answers1

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.

Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 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. – B Robster Mar 12 '13 at 16:01
  • @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)`. – Martijn Pieters Mar 12 '13 at 16:03
  • Ah. Got it. I'll try the basic way first and if that doesn't work, I'll go down that route. – B Robster Mar 12 '13 at 16:08
  • 2
    Simply setting the attribute (request.myvalue) and using getattr(request, 'myvalue', None) seems to be working fine. – B Robster Mar 12 '13 at 19:09