Webapp level context processors


Webapp level context processors

Published on Sat 04 Apr 2009 11:04 ( 11 months, 1 week ago)
Django 学习 Python

在app level来定义一部分Context processors是很有意义的,能增强webapp的自包含和可重用性:

Django Tip: Application-level context processors

Writing a replacement RequestHandler

The first time you try to reuse some context processors over and over for a particular set of views, the repetition became obvious. So let's do the natural thing and factor out the repetition. In the solution that follows, I am intentionally not calling my class RequestContext. You want to have clues when you're reading the code that this is different from the normal RequestContext. When you're reading this code in 6, 12 or 24 months, you will need the reminder that this is your own variant and not something that behaves exactly as the Django standard.

Drop this into a file somewhere:

from django import template

def make_request_context(extra_processors):
class MyRequestContext(template.RequestContext):
def __init__(*args, **kwargs):
processors = list(kwargs.pop('processors', ())
super(MyRequest, self).__init__(processors=extra_processors + processors,
*args, **kwargs)
return MyRequestContext

Now, whenever you want a RequestContext-like class that always runs a specific set of context processors, you call make_request_context(), passing it a list of the extra processors.

For example, if you have one file with all your views in it, you could put this at the top:

MY_CONTEXT_PROCESSORS = (
super.secret.special.processor.stuff,
...
)
RequestContext = make_request_context(MY_CONTEXT_PROCESSORS)

and your code will work transparently (that's why I called it RequestContext here, so that existing code won't require any change. Slightly contradicts the above advice and I wouldn't personally do this, but it's your call to make).

For bonus points, you could alter my function a little bit to cache the classes it creates and use the Borg pattern. That way if somebody wants to reuse the class with the same list of extra context processors, you don't create yet another object. A little more efficient and probably worth it if you're using this in multiple view files.


Python里的Borg Pattern原来是类似singleton:


The Borg pattern allows multiple class instances, but shares state between instances so the end user cannot tell them apart. Here is the Borg example from the Python Cookbook

class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
# and whatever else you want in your class -- that's all!


Related posts:


Search related in web:

Custom Search

RSS Feed

One click subscribe this blog in your google reader!

Be social!


Want to say something here? please sign in



Blog posts link to this page
What are friends tweeting?
Tags cloud
Monthly Archives