Login

Universal JsonResponse

Author:
pietras
Posted:
July 17, 2009
Language:
Python
Version:
1.0
Tags:
ajax view json response
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. Syndication Feed for JSON by cato 2 years, 6 months ago
  2. JSON Decimal encoder by roxeteer 4 years, 2 months ago
  3. sqltojson by amitu 6 years, 3 months ago
  4. universal JSONResponse by guetux 4 years, 2 months ago
  5. JSON View Decorator by bryanpieper 4 years, 11 months ago

Comments

Please login first before commenting.