Decorator for determining HTTP response from a view
- by polera
I want to create a decorator that will allow me to return a raw or "string" representation of a view if a GET parameter "raw" equals "1". The concept works, but I'm stuck on how to pass context to my renderer. Here's what I have so far:
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template.loader import render_to_string
def raw_response(template):
def wrap(view):
def response(request,*args,**kwargs):
if request.method == "GET":
try:
if request.GET['raw'] == "1":
render = HttpResponse(render_to_string(template,{}),content_type="text/plain")
return render
except Exception:
render = render_to_response(template,{})
return render
return response
return wrap
Currently, the {} is there just as a place holder. Ultimately, I'd like to be able to pass a dict like this:
@raw_response('my_template_name.html')
def view_name(request):
render({"x":42})
Any assistance is appreciated.