blob: 61c7c397f751a0d1c3a469ce1d0902d5b5512149 [file] [log] [blame]
srikanth116e6e82014-08-19 07:22:37 -07001#
2# Copyright (c) 2013 Big Switch Networks, Inc.
3#
4# Licensed under the Eclipse Public License, Version 1.0 (the
5# "License"); you may not use this file except in compliance with the
6# License. You may obtain a copy of the License at
7#
8# http://www.eclipse.org/legal/epl-v10.html
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13# implied. See the License for the specific language governing
14# permissions and limitations under the License.
15#
16
17from django.http import HttpResponseForbidden, HttpResponse
18from django.utils.simplejson import JSONEncoder
19from django.utils.encoding import force_unicode
20from django.db.models.base import ModelBase
21from django.utils.simplejson import dumps
22
23class JsonResponse(HttpResponse):
24 """A HttpResponse subclass that creates properly encoded JSON response"""
25
26 def __init__(self, content='', json_opts={},
27 mimetype="application/json", *args, **kwargs):
28
29 if content is None: content = []
30 content = serialize_to_json(content,**json_opts)
31 super(JsonResponse,self).__init__(content,mimetype,*args,**kwargs)
32
33class JsonEncoder(JSONEncoder):
34 """A JSONEncoder subclass that also handles querysets and models objects."""
35
36 def default(self,o):
37 # this handles querysets and other iterable types
38 try: iterable = iter(o)
39 except TypeError: pass
40 else: return list(iterable)
41
42 # this handlers Models objects
43 try: isinstance(o.__class__,ModelBase)
44 except Exception: pass
45 else: return force_unicode(o)
46
47 # delegate the rest to JSONEncoder
48 return super(JsonEncoder,self).default(obj)
49
50def serialize_to_json(obj,*args,**kwargs):
51 """A wrapper for dumps with defaults as:
52 ensure_ascii=False
53 cls=JsonEncoder"""
54
55 kwargs['ensure_ascii'] = kwargs.get('ensure_ascii', False)
56 kwargs['cls'] = kwargs.get('cls', JsonEncoder)
57 return dumps(obj,*args,**kwargs)
58
59def as_kwargs(qdict):
60 kwargs = {}
61 for k,v in qdict.items():
62 kwargs[str(k)] = v
63 return kwargs