2009-10-11 12:47:39 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# vi:si:et:sw=4:sts=4:ts=4
|
2010-02-08 15:04:54 +00:00
|
|
|
from django.http import HttpResponse, Http404
|
2010-01-22 23:06:33 +00:00
|
|
|
try:
|
2010-02-08 15:04:54 +00:00
|
|
|
import simplejson as json
|
2010-01-22 23:06:33 +00:00
|
|
|
except ImportError:
|
2010-02-08 15:04:54 +00:00
|
|
|
from django.utils import simplejson as json
|
2009-10-11 12:47:39 +00:00
|
|
|
from django.conf import settings
|
|
|
|
|
2010-02-08 16:07:32 +00:00
|
|
|
class HttpErrorJson(Http404):
|
2010-02-08 15:00:28 +00:00
|
|
|
def __init__(self, response):
|
|
|
|
self.response = response
|
|
|
|
|
2010-02-10 13:08:51 +00:00
|
|
|
def json_response(data={}, status=200, text='ok'):
|
2010-02-10 13:58:45 +00:00
|
|
|
return {'status': {'code': status, 'text': text}, 'data': data}
|
2010-02-10 13:08:51 +00:00
|
|
|
|
2010-01-26 13:55:01 +00:00
|
|
|
def render_to_json_response(dictionary, content_type="text/json", status=200):
|
2009-10-11 12:47:39 +00:00
|
|
|
indent=None
|
|
|
|
if settings.DEBUG:
|
|
|
|
content_type = "text/javascript"
|
|
|
|
indent = 2
|
2010-01-29 11:20:24 +00:00
|
|
|
if settings.JSON_DEBUG:
|
2010-02-08 15:04:54 +00:00
|
|
|
print json.dumps(dictionary, indent=2)
|
2010-01-26 13:55:01 +00:00
|
|
|
if 'status' in dictionary and 'code' in dictionary['status']:
|
|
|
|
status = dictionary['status']['code']
|
2010-02-08 15:04:54 +00:00
|
|
|
return HttpResponse(json.dumps(dictionary, indent=indent),
|
2010-01-29 11:20:24 +00:00
|
|
|
content_type=content_type, status=status)
|
2009-10-11 12:47:39 +00:00
|
|
|
|
2010-01-29 11:20:24 +00:00
|
|
|
def get_object_or_404_json(klass, *args, **kwargs):
|
|
|
|
from django.shortcuts import _get_queryset
|
|
|
|
queryset = _get_queryset(klass)
|
|
|
|
try:
|
|
|
|
return queryset.get(*args, **kwargs)
|
|
|
|
except queryset.model.DoesNotExist:
|
2010-02-08 15:00:28 +00:00
|
|
|
response = {'status': {'code': 404,
|
2010-02-08 15:04:54 +00:00
|
|
|
'text': '%s not found' % queryset.model._meta.object_name}}
|
2010-02-08 16:07:32 +00:00
|
|
|
raise HttpErrorJson(response)
|
2010-02-08 15:04:54 +00:00
|
|
|
|