diff --git a/oxdjango/middleware.py b/oxdjango/middleware.py new file mode 100644 index 0000000..66d6be9 --- /dev/null +++ b/oxdjango/middleware.py @@ -0,0 +1,13 @@ +# -*- coding: utf-8 -*- +# vi:si:et:sw=4:sts=4:ts=4 + +from shortcuts import Http404Json, render_to_json_response + +class ExceptionMiddleware(object): + + def process_exception(self, request, exception): + if isinstance(exception, Http404Json): + return render_to_json_response(exception.response) + else: + return None + diff --git a/oxdjango/shortcuts.py b/oxdjango/shortcuts.py index a00e240..6c95cff 100644 --- a/oxdjango/shortcuts.py +++ b/oxdjango/shortcuts.py @@ -1,13 +1,17 @@ # -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 -from django.http import HttpResponse, Http404 +from django.http import HttpResponse, Http404, HttpResponseNotFound try: import simplejson except ImportError: from django.utils import simplejson from django.conf import settings +class Http404Json(Http404): + def __init__(self, response): + self.response = response + def render_to_json_response(dictionary, content_type="text/json", status=200): indent=None if settings.DEBUG: @@ -27,6 +31,6 @@ def get_object_or_404_json(klass, *args, **kwargs): return queryset.get(*args, **kwargs) except queryset.model.DoesNotExist: #FIXME: how to raise exception that will only output given result - results = simplejson.dumps({'status': {'code': 404, - 'text': '%s not found' % queryset.model._meta.object_name}}) - raise Http404(results) + response = {'status': {'code': 404, + 'text': '%s not found' % queryset.model._meta.object_name}} + raise Http404Json(response)