elfs: (Default)
[personal profile] elfs

We frequently write little functions that populate the Django context, and sometimes we want that context to be site-wide, and we want every page and every Ajax handler, basically everything that takes a request and spews a response, in our application to have access to that information.  It might the user’s authentication, or his authorization, or some profile information.  Or it might be environmental: a site might have figured out what time it is on the user’s site, and will adjust backgrounds and themes accordingly.

The context might be a simple variable.  I have an example right here: is the browser you’re using good enough?  (I know, this is considered Bad Form, but it’s what I have to work with) .  The function has the simple name, need_browser_warning.  The context key may as well have the same name.  Using a constant for the context key is the usual pattern; this ensures the Django programmer won’t get it wrong more than once, at least on the view side.  (The template is another issue entirely.  Set your TEMPLATE_STRING_IF_INVALID in settings.py!)

I wanted something more clever in my context processor.  Here’s sickly clever:

import inspect
def need_browser_warning(request):
    return { inspect.currentframe().f_code.co_name:
        not adequate_browser(request.META.get('HTTP_USER_AGENT')) }

Yeah, that’s a little twisted.  It guarantees that the name of the context key is “need_browser_warning“, and the value is True or False depending upon what the function “adequate_browser” returns, which is what we want, so it’s all good.

Obviously, this isn’t good for everything.  Some context processors handle many, many values.  But for a one-key, this is a nifty way of ensuring name consistency.

This entry was automatically cross-posted from Elf's technical journal, ElfSternberg.com

Date: 2009-09-17 07:25 pm (UTC)
From: [identity profile] tamino.livejournal.com
I wonder what the performance characteristics of that are, versus something like:

def context_processor(f):
name = f.__name__
return lambda request: {name: f(request)}

@context_processor
def need_browser_warning(request):
return not adequate_browser(request.META.get('HTTP_USER_AGENT'))

Date: 2009-09-17 08:06 pm (UTC)
From: [identity profile] elfs.livejournal.com
The inspect method is significantly faster. Invoking the two with the profile active shows that the indirection of the decorator doubles run-time commitment.

Profile

elfs: (Default)
Elf Sternberg

December 2025

S M T W T F S
 12345 6
78910111213
14151617181920
21222324252627
28293031   

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Jan. 13th, 2026 08:45 am
Powered by Dreamwidth Studios