BAE BAE - 6 days ago 5
Python Question

Django: return json only for api sub-app

urls.py

urlpatterns = patterns(
url(r'^subapp1/', include('subapp1.urls', namespace='subapp1')),
url(r'^api/', include('api.urls')),
)


When
GET /api/invalid/url
sent, 404 html page returned. It seems that this is not right for REST APIs.

How to make invalid urls starting with
subapp1/
return 404 html page, and make invalid urls starting with
api/
return 404 status code and error message in json?

Is it possible to set Django to return default response based on
Accept
field in the request header? e.g. return 404 html, if
Accept text/html
, return json if
Accept application/json


Any comments welcomed. Thanks.

L.L L.L
Answer

May the following piece of codes help. From the source codes of django.views.defaults, http.HttpResponseNotFound(body, content_type=content_type) should be returned. so, checking request.path, if starting with /myapp/api, return http.HttpResponseNotFound(body, content_type='application/json'), otherwise, return default response.

from django.views.defaults import page_not_found 

    def customized_page_not_found(request, *args, **kwargs):
        if request.path.startswith('/myapp/api'):
            try:    
                from django.http import HttpResponseNotFound
                return HttpResponseNotFound( json.dumps( {'error': 'Page Not Found'} ),
                        content_type='application/json')
            except Exception as e:
                print 'Exception:', e

        return page_not_found( request, *args, **kwargs)


handler404 = customized_page_not_found

Any questions and comments welcomed.