Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

changed middleware to support custom responses #4

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
`pip install django-json-404-middleware`
40 changes: 27 additions & 13 deletions django_json_404_middleware/middleware.py
Original file line number Diff line number Diff line change
@@ -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
return response