diff --git a/README.md b/README.md index 2a73b0f..d20dca3 100644 --- a/README.md +++ b/README.md @@ -15,5 +15,36 @@ MIDDLEWARE = [ ] ``` + +Define a Response function and pass it in settings.py to `JSON404_DATA_RESPONSE` + + +```python +# in settings.py +# import mycustoomfunction +JSON_DATA_RESPONSE = mycustomfunction +``` + + +Example of custom response function + + +```python +from django.http import JsonResponse + + +def json404_response(request): + + data = { + "detail": "not found", + "title": "Not found.", + "status": 404, + "type": "{}://{}/problems/not_found/", + } + data["type"] = data["type"].format(request.scheme, request.get_host()) + return JsonResponse(data, content_type="application/problem+json", status=404) +``` + + # Installation -`pip install django-json-404-middleware` \ No newline at end of file +`pip install django-json-404-middleware` diff --git a/django_json_404_middleware/middleware.py b/django_json_404_middleware/middleware.py index 09974a6..5b46bc5 100644 --- a/django_json_404_middleware/middleware.py +++ b/django_json_404_middleware/middleware.py @@ -1,16 +1,30 @@ -from django.http import HttpResponse -import json +from django.conf import settings +from django.http import JsonResponse + + +def default_response(request): + data = {"detail": "{0} not found".format(request.path)} + return JsonResponse(data, content_type="application/json", status=404) + class JSON404Middleware(object): - """ - Returns JSON 404 instead of HTML - """ - def __init__(self, get_response): - self.get_response = get_response + """ + Returns JSON 404 instead of HTML + """ + + def __init__(self, get_response): + self.get_response = get_response + try: + self.data_function = settings.JSON404_DATA_FUNCTION + except AttributeError: + self.data_function = default_response + + def __call__(self, request): + response = self.get_response(request) + if ( + response.status_code == 404 + and "text/html" in response["content-type"] + ): + response = self.data_function(request) - def __call__(self, request): - response = self.get_response(request) - if response.status_code == 404 and 'application/json' not in response['content-type']: - data = {'detail': '{0} not found'.format(request.path)} - response = HttpResponse(json.dumps(data), content_type='application/json', status=404) - return response \ No newline at end of file + return response