1 from django import http
2 from django.utils import simplejson as json
3 from django.utils.functional import Promise
4 from django.template.loader import render_to_string
5 from datetime import datetime
7 class ExtendedEncoder(json.JSONEncoder):
9 def default(self, obj):
10 if isinstance(obj, Promise):
13 if isinstance(obj, datetime):
14 return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
16 return json.JSONEncoder.default(self, obj)
18 # shortcut for JSON reponses
19 class JSONResponse(http.HttpResponse):
21 def __init__(self, data = {}, **kwargs):
23 kwargs.pop('mimetype', None)
25 super(JSONResponse, self).__init__(
26 json.dumps(data, cls=ExtendedEncoder),
27 mimetype = "application/json", **kwargs)
31 class JSONFormInvalid(JSONResponse):
32 def __init__(self, form):
33 super(JSONFormInvalid, self).__init__(form.errors, status = 400)
35 class JSONServerError(JSONResponse):
36 def __init__(self, *args, **kwargs):
37 kwargs['status'] = 500
38 super(JSONServerError, self).__init__(*args, **kwargs)