开发者

Creating custom Exceptions that Django reacts to

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜