Skip to content

Instantly share code, notes, and snippets.

@1st
Last active December 17, 2015 13:49
Show Gist options
  • Save 1st/5619679 to your computer and use it in GitHub Desktop.
Save 1st/5619679 to your computer and use it in GitHub Desktop.
My implementation of Python decorators based on functions (not class-based decorator).
def login_required(function=None, message=None):
"""
Decorator for views that checks that the user is logged in,
or show error page with message.
>>> We can use any of this forms of decorator:
>>>
>>> # 1. without parameters
>>> @login_required
>>> def my_function(request):
>>> pass
>>>
>>> # 2. with parameters
>>> @login_required(message='This page available only for logged in users')
>>> def my_function(request):
>>> pass
@url https://github.com/1st/django-startup/
@author Anton Danilchenko <anton.danilchenko@me.com>
"""
def real_decorator(func):
def _wrapper(request, *args, **kwargs):
if request.user.is_authenticated():
return func(request, *args, **kwargs)
raise Http404(message)
return _wrapper
if function:
return real_decorator(function)
return real_decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment