I would like to return some JSON responses back instead of just returning a header with an error code. Is there a way in tastypie to handle errors like that?
Figured it out eventually. Here's a good resource to look at, if anyone else needs it. http://gist.github.com/1116962
class YourResource(ModelResource):
def wrap_view(self, view):
"""
Wraps views to return custom error codes instead of generic 500's
"""
#csrf_exempt
def wrapper(request, *args, **kwargs):
try:
callback = getattr(self, view)
response = callback(request, *args, **kwargs)
if request.is_ajax():
patch_cache_control(response, no_cache=True)
# response is a HttpResponse object, so follow Django's instructions
# to change it to your needs before you return it.
# https://docs.djangoproject.com/en/dev/ref/request-response/
return response
except (BadRequest, ApiFieldError), e:
return HttpBadRequest({'code': 666, 'message':e.args[0]})
except ValidationError, e:
# Or do some JSON wrapping around the standard 500
return HttpBadRequest({'code': 777, 'message':', '.join(e.messages)})
except Exception, e:
# Rather than re-raising, we're going to things similar to
# what Django does. The difference is returning a serialized
# error message.
return self._handle_500(request, e)
return wrapper
You could overwrite tastypie's Resource method _handle_500(). The fact that it starts with an underscore indeed indicates that this is a "private" method and shouldn't be overwritten, but I find it a cleaner way than having to overwrite wrap_view() and replicate a lot of logic.
This is the way I use it:
from tastypie import http
from tastypie.resources import ModelResource
from tastypie.exceptions import TastypieError
class MyResource(ModelResource):
class Meta:
queryset = MyModel.objects.all()
fields = ('my', 'fields')
def _handle_500(self, request, exception):
if isinstance(exception, TastypieError):
data = {
'error_message': getattr(
settings,
'TASTYPIE_CANNED_ERROR',
'Sorry, this request could not be processed.'
),
}
return self.error_response(
request,
data,
response_class=http.HttpApplicationError
)
else:
return super(MyResource, self)._handle_500(request, exception)
In this case I catch all Tastypie errors by checking if exception is an instance of TastypieError and return a JSON reponse with the message "Sorry, this request could not be processed.". If it's a different exception, I call the parent _handle_500 using super(), which will create a django error page in development mode or send_admins() in production mode.
If you want to have a specific JSON response for a specific exception, just do the isinstance() check on a specific exception. Here are all the Tastypie exceptions:
https://github.com/toastdriven/django-tastypie/blob/master/tastypie/exceptions.py
Actually I think there should be a better/cleaner way to do this in Tastypie, so I opened a ticket on their github.
Related
I have a custom Django view class that inherits from the generic DetailView.
The generic DetailView class sequentially calls its methods get_queryset, get_object, and others to generate an object to pass for a Django template.
Moreover, the generic DetailView class raises Http404 exception within these methods to deal with erroneous situations #.
except queryset.model.DoesNotExist:
raise Http404(_("No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})
What I am trying to do is simple: I want to return other HTTP status codes to the client if an error is found within these methods. However, because Http404 is the only Django HttpResponse that has a form of exception, it seems like this cannot be achieved easily.
Because HttpResponse is not an exception, I have to return it instead of raising it. Therefore, the customized method becomes the following form.
def get_object(self, queryset=None):
...
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except queryset.model.DoesNotExist:
return HttpResponseBadRequest("Bad request.")
However, above code does not send HttpResponseBadRequest to the client. Instead, it returns HttpResponseBadRequest as an object for a Django template. The client gets 200 status code with an invalid object for the template.
The only possible solution to think is writing some object-checking code within the Django template. However, I wonder if there is any better way to deal with this problem.
Since Django 3.2 we now have an exception BadRequest [Django docs] which will be turned into a HttpResponseBadRequest internally when caught, so you can try catching Http404 and raising BadRequest instead:
from django.core.exceptions import BadRequest
class MyView(SomeGenericView):
...
def get_object(self, queryset=None):
try:
return super().get_object(queryset=queryset)
except Http404 as e:
# raise BadRequest("Bad request.") from e
raise BadRequest("Bad request.")
For some previous version we can try to catch the exception at the dispatch method and return the appropriate response there:
class MyView(SomeGenericView):
...
def dispatch(self, request, *args, **kwargs):
try:
return super().dispatch(request, *args, **kwargs)
except Http404:
return HttpResponseBadRequest("Bad request.")
I'm starting to dive into DRF a little deeper of late, and I was wondering I would like to start customising the error messaging that gets return via the API for incorrect permissions, I'd like to wrap a little extra detail.
For example, if authentication credentials were not provided for an endpoint that is permission restricted, the API returns:
{
"detail": "Authentication credentials were not provided."
}
Which comes from line 171 from the rest_framework.exceptions: https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py. Really, I'd like this to be consistent with the
{
"success": false,
"message": "Authentication credentials were not provided.",
"data": null
}
So, I assume I now need to begin customising my own exceptions.
How best should I go about doing this?
Perhaps it has some tie in with default_error_messages = {} inside the serializer ...
You can override DRF's default exception handler and JSON parser on your settings.py:
REST_FRAMEWORK = {
...
'EXCEPTION_HANDLER': 'helpers.exceptions.custom_exception_handler',
'DEFAULT_RENDERER_CLASSES': [
'helpers.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
]
}
And then it's just a matter of customizing how to handle your exceptions and how to render the responses:
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Customize your exception handling here
return response
And you can use the custom JSON renderer in case you need to do any extra formatting on the response, in my case I had to add a "status_code" to the payload:
class JSONRenderer(BaseJsonRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Render `data` into JSON, returning a bytestring.
"""
<Base code from the original class...>
response = renderer_context.get('response')
if response and 200 <= response.status_code <= 299 and 'status_code' not in response.data:
response.data = Errors.success(response.data)
<Base code from the original class...>
My Errors.success(response.data) was just a simpler way to merge the success status code to the data.
There is a decorator solution that creates custom Response on each type of your exceptions:
# project/api/exceptions.py
from functools import wraps
from rest_framework import status
def handle_exceptions(func):
#wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except AuthCredentialsError as exc:
return Response(
{"message": exc.message},
status=status.HTTP_405_METHOD_NOT_ALLOWED,
)
return wrapper
# project/api/your_code.py
from project.api.exceptions import handle_exceptions
class SomeViewSet():
#handle_exceptions
def create(self, request, *args, **kwargs):
raise AuthCredentialsError("Authentication credentials were not provided")
I have a unique constraint on a database field. When a duplicate is submitted I'd like to avoid sending a 500 response. How can I catch this error in DRF and return a 4XX response instead?
I knew I needed to put a try/except block around something, but I didn't know what. I looked at the DRF code, and I saw that generics.ListCreateAPIView has a method called create. I wrote a new function inside my class called the parent create which has the same signature as the one I inherited, which called create, and I put the try/except around this function.
In the end it looks like this:
class MyModelList(generics.ListCreateAPIView):
def get_queryset(self):
return MyModel.objects.all()
def create(self, request, *args, **kwargs):
try:
return super(MyModelList, self).create(request, *args, **kwargs)
except IntegrityError:
raise CustomUniqueException
serializer_class = MyModelSerializer
I hope this helps someone.
If you want this only for this view override handle_exception:
class MyAPIView(APIView):
...
def handle_exception(self, exc):
"""
Handle any exception that occurs, by returning an appropriate
response,or re-raising the error.
"""
...
To handle it for all views, you can define a global exception handler, see here: http://www.django-rest-framework.org/api-guide/exceptions
Does anyone have opinions on the best way of having middleware catch exceptions, and instead of rendering the error into a HTML template, to return a JSON object? Currently I have the middleware below that catches exceptions, and if it can find an extra user error message, puts that onto the request (that the template then picks up).
class ExceptionUserErrorMessageMiddleware(object):
def process_exception(self, request, exception):
""" if the exception has information relevant to the user, then
tack that onto the request object"""
theFormat = djrequest.get_getvar(request, settings.FORMAT_PARAM, "")
msg = getMessage(exception)
if msg:
setattr(request, USER_ERROR_MESSAGE_ATTR, msg)
if theFormat == "json":
print "do something"
What's the best way of returning a json object here? Should I set any additional headers?
Is there a way of doing the same for exceptional circumstances that don't pass through middleware (I'm pretty sure 404 doesn't, are there any others)?
What we do on our project MapIt - https://github.com/mysociety/mapit - for doing this is to raise an Exception to a middleware, as you say, which then directly returns either an HTML template or a JSON object depending on the format provided by the request. You can view the code at https://github.com/mysociety/mapit/blob/master/mapit/middleware/view_error.py
In terms of additional headers, our output_json function sets the Content-Type on the response to 'application/json; charset=utf-8'.
For the 404 case, we have our own get_object_or_404 function that wraps get_object_or_404 and converts a Django Http404 exception into our own exception that will then correctly return JSON if appropriate to the request.
from django.shortcuts import get_object_or_404 as orig_get_object_or_404
def get_object_or_404(klass, format='json', *args, **kwargs):
try:
return orig_get_object_or_404(klass, *args, **kwargs)
except http.Http404, e:
raise ViewException(format, str(e), 404)
For my site I created an abstract Model which implements model-level read permissions. That part of the system is completed and works correctly. One of the methods the permissioned model exposes is is_safe(user) which can manually test if a user is allowed to view that model or not.
What I would like to do is add a method to the effect of continue_if_safe which can be called on any model instance, and instead of returning a boolean value like is_safe it would first test if the model can be viewed or not, then in the case of False, it would redirect the user, either to the login page if they aren't already logged in or return a 403 error if they are logged in.
Ideal usage:
model = get_object_or_404(Model, slug=slug)
model.continue_if_safe(request.user)
# ... remainder of code to be run if it's safe down here ...
I peeked at how the get_object_or_404 works, and it throws an Http404 error which seems to make sense. However, the problem is that there don't seem to be equivalent redirect or 403 errors. What's the best way to go about this?
(non-working) continue_if_safe method:
def continue_if_safe(self, user):
if not self.is_safe(user):
if user.is_authenticated():
raise HttpResponseForbidden()
else:
raise HttpResponseRedirect('/account/')
return
Edit -- The Solution
The code for the final solution, in case other "stackers" need some help with this:
In the Abstract Model:
def continue_if_safe(self, user):
if not self.is_safe(user):
raise PermissionDenied()
return
Views are caught by the middleware:
class PermissionDeniedToLoginMiddleware(object):
def process_exception(self, request, exception):
if type(exception) == PermissionDenied:
if not request.user.is_authenticated():
return HttpResponseRedirect('/account/?next=' + request.path)
return None
Usage in the view (very short and sweet):
model = get_object_or_404(Model, slug=slug)
model.continue_if_safe(request.user)
For the forbidden (403) error, you could raise a PermissionDenied exception (from django.core.exceptions).
For the redirecting behaviour, there's no built-in way to deal with it the way you describe in your question. You could write a custom middleware that will catch your exception and redirect in process_exception.
I've made a little middleware that return whatever your Exception class's render method returns. Now you can throw custom exception's (with render methods) in any of your views.
class ProductNotFound(Exception):
def render(self, request):
return HttpResponse("You could ofcourse use render_to_response or any response object")
pip install -e git+http://github.com/jonasgeiregat/django-excepted.git#egg=django_excepted
And add django_excepted.middleware.ExceptionHandlingMiddleware to your MIDDLEWARE_CLASSES.
Django annoying has a solution for this:
from annoying.exceptions import Redirect
...
raise Redirect('/') # or a url name, etc
You want to use decorators for this. Look up login_required for an example. Basically the decorator will allow you check check the safety and then return HttpResponseRedirect() if its not safe.
Your code will end up looking something like this:
#safety_check:
def some_view(request):
#Do Stuff