2016-11-15 4 views
2

urls.pyDjango: return Json nur für api Unter App

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

Wenn GET /api/invalid/url gesendet, 404 HTML-Seite zurückgegeben. Es scheint, dass dies für REST-APIs nicht richtig ist.

Wie machen ungültige URLs beginnend mit subapp1/ html Seite 404 zurück, und machen ungültige URLs beginnend mit api/ Rückgabe 404 Statuscode und Fehlermeldung in JSON?

Kann Django so eingestellt werden, dass die Standardantwort auf dem Feld Accept im Anforderungsheader zurückgegeben wird? z.B. zurück 404 html, wenn Accept text/html, zurück json wenn Accept application/json

Alle Kommentare willkommen. Vielen Dank.

Antwort

1

können die folgenden Stück Code Hilfe.

Aus den Quellcodes django.views.defaults sollte http.HttpResponseNotFound(body, content_type=content_type) zurückgegeben werden. Überprüfen Sie daher request.path, wenn Sie mit /topApp/api beginnen, geben Sie http.HttpResponseNotFound(body, content_type='application/json') zurück, andernfalls geben Sie default Antwort zurück.

Immer, request.path beginnt mit /topApp, nicht IP oder Hostname. Und die Eingangsparameter (siehe link) beinhalten request, exception, template_name=ERROR_404_TEMPLATE_NAME, die in meinen Codes von *args, **kwargs behandelt werden sollten.

from django.views.defaults import page_not_found 

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

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


handler404 = customized_page_not_found 

Alle Fragen und Kommentare willkommen.

1

Edit: beide Kontrollen URL und Content-Typ

my_project/urls.py

from django.conf.urls import url, include, handler404 
from my_app import views 

handler404 = views.page_not_found 

my_app/views.py

from django.http import HttpResponseNotFound, JsonResponse 

def page_not_found(request): 
    if request.get_full_path()[1:].startswith('api') and request.content_type == 'application/json': 
     return JsonResponse({'not': 'found'}) 
    return HttpResponseNotFound('Not found') 

Docs: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views

+0

Wie überprüft man den 'Inhaltstyp'? Danke – BAE

+0

@BAE request.content_type in der Antwort bearbeitet. –