10π
One way of returning json would be to catch the exceptions and return proper response (assuming youβre using JSONParser
as default parser):
from rest_framework.response import Response
from rest_framework import status
@api_view(['POST'])
@permission_classes((IsAuthenticated,))
def downloadData(request):
try:
print request.POST['tables']
except:
return Response({'error': True, 'content': 'Exception!'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response({'error': False})
UPDATE
For global wise use-case the correct idea would be to put the json response in exception middleware.
You can find example in this blog post.
In your case you need to return DRF response, so if any exception gets raised it will end up in the process_exception
:
from rest_framework.response import Response
class ExceptionMiddleware(object):
def process_exception(self, request, exception):
return Response({'error': True, 'content': exception}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
7π
You can replace the default error handlers by specifying a custom handler in your URLConf as documented here
Something like this:
# In urls.py
handler500 = 'my_app.views.api_500'
and:
# In my_app.views
def api_500(request):
response = HttpResponse('{"detail":"An Error Occurred"}', content_type="application/json", status=500)
return response
I hope that helps.
- Django ListView customising queryset
- Can't pip install mysql-python
- How do I hide the field label for a HiddenInput widget in Django Admin?
- How do you actually use a reusable django app in a project?
- How do I simulate connection errors and request timeouts in python unit tests
4π
As you can see in the documentation.
All you need to do is configure settings.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.parsers.JSONParser',
),
'EXCEPTION_HANDLER': 'core.views.api_500_handler',
}
And pointing to a view that will recieve (exception, context)
Like this:
from rest_framework.views import exception_handler
...
def api_500_handler(exception, context):
response = exception_handler(exception, context)
try:
detail = response.data['detail']
except AttributeError:
detail = exception.message
response = HttpResponse(
json.dumps({'detail': detail}),
content_type="application/json", status=500
)
return response
My implementation is like this because if a expected rest framework exception is raised, like a βexceptions.NotFoundβ, exception.message
will be empty. Thats why Im first calling to exception_handler
of rest framework. If is an expected exception, I will get its message.
- Moving from direct_to_template to new TemplateView in Django
- In python django how do you print out an object's introspection? The list of all public methods of that object (variable and/or functions)?