Decorator for determining HTTP response from a view

Posted by polera on Stack Overflow See other posts from Stack Overflow or by polera
Published on 2010-04-02T15:45:42Z Indexed on 2010/04/02 16:03 UTC
Read the original article Hit count: 282

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about django

Related posts about python