Created
September 15, 2011 21:22
-
-
Save dstufft/1220512 to your computer and use it in GitHub Desktop.
Mixins vs Decorators for Django
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
class ViewDecorator(object): | |
def __init__(self, decorator_class): | |
self.decorator_class = decorator_class | |
def __call__(self, *args, **kwargs): | |
# Pretend that there is a generic decorator wrapper here | |
pass | |
login_required = ViewDecorator(LoginRequired) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
from django.http import HttpResponseRedirect | |
class LoginRequired(object): | |
def dispatch(self, request, *args, **kwargs): | |
if self.check_logged_in(request.user): | |
return super(LoginRequired, self).dispatch(request, *args, **kwargs) | |
else: | |
return self.not_logged_in(self): | |
def check_logged_in(self, user): | |
return user.is_authenticated() | |
def not_logged_in(self): | |
return HttpResponseRedirect(settings.LOGIN_URL) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@login_required | |
def function_based_view(self, request): | |
return HttpResponse("Testing") | |
class ClassBasedView(LoginRequired, TemplateView): | |
template_name = "secret.html" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment