def get_article_from_id(view):
"""
Retrieves a specific article, passing it to the view directly
"""
def wrapper(request, id, *args, **kwargs):
article = get_object_or_404(Article, id=int(id))
return view(request, article=article, *args, **kwargs)
return wraps(view)(wrapper)
def content_type(c_type):
"""
Overrides the Content-Type provided by the view.
Accepts a single argument, the new Content-Type
value to be written to the outgoing response.
"""
def decorator(view):
def wrapper(request, *args, **kwargs):
response = view(request, *args, **kwargs)
response['Content-Type'] = c_type
return wraps(view)(wrapper)
return decorator
def dual_format(template_name):
def decorator(view):
def wrapper(request, *args, **kwargs):
data = view(request, *args, **kwargs)
if request.is_ajax():
json = simplejson.dumps(data, cls=DjangoJSONEncoder)
return HttpResponse(json)
else:
context = RequestContext(request)
return render_to_response(template_name, data, context)
return wraps(view)(wrapper)
return decorator
def logged(view):
"""
Logs any errors that occurred during the view
in a special model design for app-specific errors
"""
def wrapper(request, *args, **kwargs):
try:
return view(request, *args, **kwargs)
except Exception, e:
# Log the entry using the application’s Entry model
Entry.objects.create(path=request.path, type='View exception', description=str(e))
# Re-raise it so standard error handling still applies
raise
return wraps(view)(wrapper)
Jul 14, 2011
Decorators ideas
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment