user973758
user973758

Reputation: 727

Django python - how to put all HttpResponses through a function

I have urls.py which routes a HttpRequest to a particular view function. These view functions all return a dictionary object. How can I pass all these return objects through a function which dumps to Json and wraps in an HttpResponse?

Thanks

Upvotes: 0

Views: 193

Answers (3)

Pratik Mandrekar
Pratik Mandrekar

Reputation: 9568

Use Django Middleware to process your response object. Implement the process_response method in your custom middleware. Use the dictionary that is created by the view and convert it to the json you desire. Then pass it to the below function which will ensure the actual response received is json.

def render_json_response(data):
    """Sends an HttpResponse with the X-JSON header and the right mimetype."""
    resp = HttpResponse(data, mimetype=("application/json;"))
    resp['X-JSON'] = data
    return resp

Also discovered this ajax_request decorator - returns JsonResponse with dict as content available in the Django Annoying project

Upvotes: 0

Dirk Eschler
Dirk Eschler

Reputation: 2569

How about subclassing HttpResponse? I'm using this in views to return json:

import simplejson
from django.http import HttpResponse

class JsonResponse(HttpResponse):
    def __init__(self, data):
        super(JsonResponse, self).__init__(
            content=simplejson.dumps(data),
            mimetype='application/json; charset=utf8')

Upvotes: 0

Serhii Holinei
Serhii Holinei

Reputation: 5864

Maybe a render_decorator is what you want. Usage:

@render('index.html', ('json',))
def my_view(request)
    #do something
    return {'key': 'value'}

Or this snippet, which is used on a function that returns a dict to get a JSON view.

Upvotes: 3

Related Questions