This decorator makes views even easier:
Code:
def page(template=None, context=None, **decorator_args):
def _wrapper(fn):
def _innerWrapper(request, *args, **kw):
context_dict = decorator_args.copy()
g = fn(request, *args, **kw)
if not hasattr(g, 'next'): #Is this a generator? Otherwise make her a tuple!
g = (g,)
for i in g:
if isinstance(i, httpwrappers.HttpResponse):
return i
if type(i) == type(()):
context_dict[i[0]] = i[1]
else:
context_dict.update(i)
template_name = context_dict.get("template", template)
context_instance = context_dict.get("context", context)
return render_to_response(template_name, context_dict, context_instance)
return _innerWrapper
return _wrapper
Usage:
@page("polls/index") #The decorator function takes the template to be used.
def index(request):
latest_poll_list = polls.get_list(order_by=['-pub_date'], limit=5)
yield {'latest_poll_list': latest_poll_list}
yield {'title': 'Latest Poll Listing'} # We can yield at multiple places in the function.
Or one could yield the locals():
@page("polls/index", title='Latest Poll Listing') #Extra keyword arguments are sent in the context.
def index(request):
latest_poll_list = polls.get_list(order_by=['-pub_date'], limit=5)
yield locals() #This yeilds all the local variables, which is 'latest_poll_list', and 'request'
You can set a template mid-stream with:
@page() #We don't say what template is needed yet.
def index(request):
latest_poll_list = polls.get_list(order_by=['-pub_date'], limit=5)
if (latest_poll_list):
template = 'polls/index'
else:
template = 'polls/nopolls' # We could also send 'context' which changes what context we use.
yield locals()
You can yield a response to have it immediately returned:
@page('polls/index')
def index(request):
latest_poll_list = polls.get_list(order_by=['-pub_date'], limit=5)
if (not latest_poll_list):
yield httpwrappers.HttpResponseRedirect("/home/") #Since we don't have any latest polls, redirect to home.
return #Don't yield anything else, we're done here.
yield locals()
Last modified
20 years ago
Last modified on Jan 11, 2006, 2:28:48 PM
Note:
See TracWiki
for help on using the wiki.