Login

Universal JsonResponse

Author:
pietras
Posted:
July 17, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

Serves serialized QuerySet or other list passed in data parameter as json content.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from django.core.serializers.json import DjangoJSONEncoder
import simplejson as json
from django.db.models.query import QuerySet
from django.http import HttpResponse
from django.core import serializers 

class JsonResponse(HttpResponse):
	error = ""
	__data = []
	
	def __set_data(self, data):
		self.__data = (isinstance(data, QuerySet) or hasattr(data[0], '_meta'))\
		 	and serializers.serialize('python', data) or data
	
	data = property(fset = __set_data)

	def __get_container(self):
		return json.dumps( 
			{
				"data": self.__data, 
				"error":self.error,
			}, cls = DjangoJSONEncoder)
			
	def __set_container(self, val):
		pass
	
	_container = property(__get_container, __set_container)
	
	def __init__(self, *args, **kwargs):
		kwargs["mimetype"] = "application/javascript"

		if "data" in kwargs:
			self.data = kwargs.pop("data")
			
		if "error" in kwargs:
			self.error = kwargs.pop("error")
		
		super(JsonResponse, self).__init__(*args, **kwargs)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months, 1 week ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.