python-oxdjango/oxdjango/shortcuts.py

37 lines
1.3 KiB
Python
Raw Normal View History

2009-10-11 14:47:39 +02:00
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
from django.http import HttpResponse, Http404, HttpResponseNotFound
2010-01-23 10:06:33 +11:00
try:
import simplejson
except ImportError:
from django.utils import simplejson
2009-10-11 14:47:39 +02:00
from django.conf import settings
class Http404Json(Http404):
def __init__(self, response):
self.response = response
2010-01-26 19:25:01 +05:30
def render_to_json_response(dictionary, content_type="text/json", status=200):
2009-10-11 14:47:39 +02:00
indent=None
if settings.DEBUG:
content_type = "text/javascript"
indent = 2
2010-01-29 16:50:24 +05:30
if settings.JSON_DEBUG:
print simplejson.dumps(dictionary, indent=2)
2010-01-26 19:25:01 +05:30
if 'status' in dictionary and 'code' in dictionary['status']:
status = dictionary['status']['code']
2010-01-29 16:50:24 +05:30
return HttpResponse(simplejson.dumps(dictionary, indent=indent),
content_type=content_type, status=status)
2009-10-11 14:47:39 +02:00
2010-01-29 16:50:24 +05:30
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:
#FIXME: how to raise exception that will only output given result
response = {'status': {'code': 404,
'text': '%s not found' % queryset.model._meta.object_name}}
raise Http404Json(response)