Webapp level context processors
在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 templatedef 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 MyRequestContextNow, 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:
- Looking for partners to attend Startup Weekend Seattle in Mar 19-21
- app-engine-patch is now officially dead
- 警惕Context的push()和pop()
- GAE的blobstore初步体验
- Seattle: 开放P2P云计算平台 / 未来的anti GFW利器?
- Northwest Python Day 2010
- App Engine Patch对支持Generic View的一个问题和解决方案
- Reusable webapp的思考(5)
- 用Javascript实现漂亮的字体显示
- python module path含有. 的问题
Search related in web: