Python django.utils.decorators.available_attrs() Examples

The following are 30 code examples of django.utils.decorators.available_attrs(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.decorators , or try the search function .
Example #1
Source File: decorator.py    From zulip with Apache License 2.0 7 votes vote down vote up
def user_passes_test(test_func: Callable[[HttpResponse], bool], login_url: Optional[str]=None,
                     redirect_field_name: str=REDIRECT_FIELD_NAME) -> Callable[[ViewFuncT], ViewFuncT]:
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """
    def decorator(view_func: ViewFuncT) -> ViewFuncT:
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request: HttpRequest, *args: object, **kwargs: object) -> HttpResponse:
            if test_func(request):
                return view_func(request, *args, **kwargs)
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urllib.parse.urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urllib.parse.urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return cast(ViewFuncT, _wrapped_view)  # https://github.com/python/mypy/issues/1927
    return decorator 
Example #2
Source File: clickjacking.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def xframe_options_exempt(view_func):
    """
    Modifies a view function by setting a response variable that instructs
    XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header.

    e.g.

    @xframe_options_exempt
    def some_view(request):
        ...
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        resp.xframe_options_exempt = True
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #3
Source File: decorators.py    From devops with MIT License 6 votes vote down vote up
def login_required(func=None, redirect_field_name="next", login_url=None):
    """
    Decorator for views that checks that the user is logged in, redirecting
    to the log in page if necessary.
    """
    def decorator(view_func):
        @functools.wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if request.user.is_authenticated():
                return view_func(request, *args, **kwargs)
            return handle_redirect_to_login(
                request,
                redirect_field_name=redirect_field_name,
                login_url=login_url
            )
        return _wrapped_view
    if func:
        return decorator(func)
    return decorator 
Example #4
Source File: vary.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def vary_on_headers(*headers):
    """
    A view decorator that adds the specified headers to the Vary header of the
    response. Usage:

       @vary_on_headers('Cookie', 'Accept-language')
       def index(request):
           ...

    Note that the header names are not case-sensitive.
    """
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner_func(*args, **kwargs):
            response = func(*args, **kwargs)
            patch_vary_headers(response, headers)
            return response
        return inner_func
    return decorator 
Example #5
Source File: vary.py    From python with Apache License 2.0 6 votes vote down vote up
def vary_on_headers(*headers):
    """
    A view decorator that adds the specified headers to the Vary header of the
    response. Usage:

       @vary_on_headers('Cookie', 'Accept-language')
       def index(request):
           ...

    Note that the header names are not case-sensitive.
    """
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner_func(*args, **kwargs):
            response = func(*args, **kwargs)
            patch_vary_headers(response, headers)
            return response
        return inner_func
    return decorator 
Example #6
Source File: decorators.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
def catch_api_exception(fun):
    """
    Like catch_exception above, but it logs the exception caught.
    """
    from api.task.utils import task_log_exception  # circular imports

    @wraps(fun, assigned=available_attrs(fun))
    def wrap(*args, **kwargs):
        try:
            return fun(*args, **kwargs)
        except Exception as e:
            logger.exception(e)
            logger.error('Got exception when running %s(%s, %s): %s.', fun.__name__, args, kwargs, e)

            for arg in args:
                if is_request(arg):
                    try:
                        task_log_exception(arg, e, task_id=getattr(e, 'task_id', None))
                    except Exception as exc:
                        logger.exception(exc)
                    break
            else:
                logger.warning('API exception could not be logged into task log')

    return wrap 
Example #7
Source File: decorators.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
def catch_exception(fun):
    """
    Used as decorator to catch all exceptions and log them without breaking the inner function.
    Can be disabled by using the fail_silently keyword argument, which won't be passed to inner function.
    """
    @wraps(fun, assigned=available_attrs(fun))
    def wrap(*args, **kwargs):
        if kwargs.pop('fail_silently', True):
            try:
                return fun(*args, **kwargs)
            except Exception as e:
                logger.exception(e)
                logger.error('Got exception when running %s(%s, %s): %s.', fun.__name__, args, kwargs, e)
        else:
            return fun(*args, **kwargs)

    return wrap 
Example #8
Source File: clickjacking.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def xframe_options_exempt(view_func):
    """
    Modifies a view function by setting a response variable that instructs
    XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header.

    e.g.

    @xframe_options_exempt
    def some_view(request):
        ...

    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        resp.xframe_options_exempt = True
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #9
Source File: clickjacking.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def xframe_options_sameorigin(view_func):
    """
    Modifies a view function so its response has the X-Frame-Options HTTP
    header set to 'SAMEORIGIN' as long as the response doesn't already have
    that header set.

    e.g.

    @xframe_options_sameorigin
    def some_view(request):
        ...

    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        if resp.get('X-Frame-Options', None) is None:
            resp['X-Frame-Options'] = 'SAMEORIGIN'
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #10
Source File: clickjacking.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def xframe_options_deny(view_func):
    """
    Modifies a view function so its response has the X-Frame-Options HTTP
    header set to 'DENY' as long as the response doesn't already have that
    header set.

    e.g.

    @xframe_options_deny
    def some_view(request):
        ...

    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        if resp.get('X-Frame-Options', None) is None:
            resp['X-Frame-Options'] = 'DENY'
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #11
Source File: decorators.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def is_owner(view_func):
    @wraps(view_func, assigned=available_attrs(view_func))
    def _wrapped_view(request, *args, **kwargs):
        # assume username is first arg
        if request.user.is_authenticated():
            if request.user.username == kwargs['username']:
                return view_func(request, *args, **kwargs)
            protocol = "https" if request.is_secure() else "http"
            return HttpResponseRedirect("%s://%s" % (protocol,
                                                     request.get_host()))
        path = request.build_absolute_uri()
        login_url = request.build_absolute_uri(settings.LOGIN_URL)
        # If the login url is the same scheme and net location then just
        # use the path as the "next" url.
        login_scheme, login_netloc = urlparse.urlparse(login_url)[:2]
        current_scheme, current_netloc = urlparse.urlparse(path)[:2]
        if ((not login_scheme or login_scheme == current_scheme) and
                (not login_netloc or login_netloc == current_netloc)):
            path = request.get_full_path()
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(path, None, REDIRECT_FIELD_NAME)
    return _wrapped_view 
Example #12
Source File: clickjacking.py    From python2017 with MIT License 6 votes vote down vote up
def xframe_options_exempt(view_func):
    """
    Modifies a view function by setting a response variable that instructs
    XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header.

    e.g.

    @xframe_options_exempt
    def some_view(request):
        ...
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        resp.xframe_options_exempt = True
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #13
Source File: clickjacking.py    From python with Apache License 2.0 6 votes vote down vote up
def xframe_options_deny(view_func):
    """
    Modifies a view function so its response has the X-Frame-Options HTTP
    header set to 'DENY' as long as the response doesn't already have that
    header set.

    e.g.

    @xframe_options_deny
    def some_view(request):
        ...
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        if resp.get('X-Frame-Options') is None:
            resp['X-Frame-Options'] = 'DENY'
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #14
Source File: clickjacking.py    From python2017 with MIT License 6 votes vote down vote up
def xframe_options_sameorigin(view_func):
    """
    Modifies a view function so its response has the X-Frame-Options HTTP
    header set to 'SAMEORIGIN' as long as the response doesn't already have
    that header set.

    e.g.

    @xframe_options_sameorigin
    def some_view(request):
        ...
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        if resp.get('X-Frame-Options') is None:
            resp['X-Frame-Options'] = 'SAMEORIGIN'
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #15
Source File: clickjacking.py    From python with Apache License 2.0 6 votes vote down vote up
def xframe_options_sameorigin(view_func):
    """
    Modifies a view function so its response has the X-Frame-Options HTTP
    header set to 'SAMEORIGIN' as long as the response doesn't already have
    that header set.

    e.g.

    @xframe_options_sameorigin
    def some_view(request):
        ...
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        if resp.get('X-Frame-Options') is None:
            resp['X-Frame-Options'] = 'SAMEORIGIN'
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #16
Source File: clickjacking.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def xframe_options_sameorigin(view_func):
    """
    Modifies a view function so its response has the X-Frame-Options HTTP
    header set to 'SAMEORIGIN' as long as the response doesn't already have
    that header set.

    e.g.

    @xframe_options_sameorigin
    def some_view(request):
        ...
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        if resp.get('X-Frame-Options') is None:
            resp['X-Frame-Options'] = 'SAMEORIGIN'
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #17
Source File: clickjacking.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def xframe_options_deny(view_func):
    """
    Modifies a view function so its response has the X-Frame-Options HTTP
    header set to 'DENY' as long as the response doesn't already have that
    header set.

    e.g.

    @xframe_options_deny
    def some_view(request):
        ...
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        if resp.get('X-Frame-Options') is None:
            resp['X-Frame-Options'] = 'DENY'
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #18
Source File: vary.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def vary_on_headers(*headers):
    """
    A view decorator that adds the specified headers to the Vary header of the
    response. Usage:

       @vary_on_headers('Cookie', 'Accept-language')
       def index(request):
           ...

    Note that the header names are not case-sensitive.
    """
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner_func(*args, **kwargs):
            response = func(*args, **kwargs)
            patch_vary_headers(response, headers)
            return response
        return inner_func
    return decorator 
Example #19
Source File: clickjacking.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def xframe_options_exempt(view_func):
    """
    Modifies a view function by setting a response variable that instructs
    XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header.

    e.g.

    @xframe_options_exempt
    def some_view(request):
        ...

    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        resp.xframe_options_exempt = True
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #20
Source File: clickjacking.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def xframe_options_sameorigin(view_func):
    """
    Modifies a view function so its response has the X-Frame-Options HTTP
    header set to 'SAMEORIGIN' as long as the response doesn't already have
    that header set.

    e.g.

    @xframe_options_sameorigin
    def some_view(request):
        ...

    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        if resp.get('X-Frame-Options', None) is None:
            resp['X-Frame-Options'] = 'SAMEORIGIN'
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #21
Source File: clickjacking.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def xframe_options_deny(view_func):
    """
    Modifies a view function so its response has the X-Frame-Options HTTP
    header set to 'DENY' as long as the response doesn't already have that
    header set.

    e.g.

    @xframe_options_deny
    def some_view(request):
        ...

    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        if resp.get('X-Frame-Options', None) is None:
            resp['X-Frame-Options'] = 'DENY'
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #22
Source File: vary.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def vary_on_headers(*headers):
    """
    A view decorator that adds the specified headers to the Vary header of the
    response. Usage:

       @vary_on_headers('Cookie', 'Accept-language')
       def index(request):
           ...

    Note that the header names are not case-sensitive.
    """
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner_func(*args, **kwargs):
            response = func(*args, **kwargs)
            patch_vary_headers(response, headers)
            return response
        return inner_func
    return decorator 
Example #23
Source File: decorators.py    From ontask_b with MIT License 6 votes vote down vote up
def lti_role_required(
    allowed_roles: List[str],
    redirect_url: str = reverse_lazy('not_authorized'),
    raise_exception: Optional[bool] = False,
) -> Callable:
    def decorator(view_func: Callable) -> Callable:
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if is_allowed(request, allowed_roles, raise_exception):
                return view_func(request, *args, **kwargs)

            return redirect(redirect_url)

        return _wrapped_view

    return decorator 
Example #24
Source File: vary.py    From python2017 with MIT License 6 votes vote down vote up
def vary_on_headers(*headers):
    """
    A view decorator that adds the specified headers to the Vary header of the
    response. Usage:

       @vary_on_headers('Cookie', 'Accept-language')
       def index(request):
           ...

    Note that the header names are not case-sensitive.
    """
    def decorator(func):
        @wraps(func, assigned=available_attrs(func))
        def inner_func(*args, **kwargs):
            response = func(*args, **kwargs)
            patch_vary_headers(response, headers)
            return response
        return inner_func
    return decorator 
Example #25
Source File: clickjacking.py    From python2017 with MIT License 6 votes vote down vote up
def xframe_options_deny(view_func):
    """
    Modifies a view function so its response has the X-Frame-Options HTTP
    header set to 'DENY' as long as the response doesn't already have that
    header set.

    e.g.

    @xframe_options_deny
    def some_view(request):
        ...
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        if resp.get('X-Frame-Options') is None:
            resp['X-Frame-Options'] = 'DENY'
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #26
Source File: clickjacking.py    From python with Apache License 2.0 6 votes vote down vote up
def xframe_options_exempt(view_func):
    """
    Modifies a view function by setting a response variable that instructs
    XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header.

    e.g.

    @xframe_options_exempt
    def some_view(request):
        ...
    """
    def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        resp.xframe_options_exempt = True
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #27
Source File: security.py    From eventoL with GNU General Public License v3.0 5 votes vote down vote up
def is_activity_public():
    """Return True if activities are public.

    If activities are private only will return true for collaborator users or activity owner"""
    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            activity_id = kwargs['activity_id']
            user = request.user
            activity = get_object_or_404(Activity, pk=activity_id)
            event_slug = kwargs['event_slug']

            if any([
                    activity.status == "2",  # Accepted
                    not settings.PRIVATE_ACTIVITIES,
                    activity.owner.user == user,
                    user.is_authenticated() and is_reviewer(user, event_slug=event_slug)
            ]):
                return view_func(request, *args, **kwargs)
            raise PermissionDenied(
                "Only organizers and collaborators are authorized "
                "to access the activities list."
            )
        return _wrapped_view

    return decorator 
Example #28
Source File: log.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def save_task_log(msg):
    """
    Decorator used by monitoring tasks. It creates a unique list-like object for collecting monitoring logs and is
    responsible for creating a task log entry after the monitoring task is finished.
    """
    def wrap(fun):
        @wraps(fun, assigned=available_attrs(fun))
        def inner(task_id, sender, **kwargs):
            logger.info('Primary task %s issued a secondary mgmt monitoring task %s', sender, task_id)
            status = None
            # Every monitoring task should collect logs
            # NOTE: However, the monitoring task is responsible for setting up the object related to the log entry
            kwargs['log'] = log = DetailLog(sender, msg)

            try:
                status = fun(task_id, sender, **kwargs)
            except Exception as exc:
                status = False
                log.add(CRITICAL, exc)
                raise exc
            finally:
                log.save(status)

            return status
        return inner
    return wrap 
Example #29
Source File: csrf.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def csrf_exempt(view_func):
    """
    Marks a view function as being exempt from the CSRF view protection.
    """
    # We could just do view_func.csrf_exempt = True, but decorators
    # are nicer if they don't have side-effects, so we return a new
    # function.
    def wrapped_view(*args, **kwargs):
        return view_func(*args, **kwargs)
    wrapped_view.csrf_exempt = True
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) 
Example #30
Source File: decorators.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = request.build_absolute_uri()
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            # If the login url is the same scheme and net location then just
            # use the path as the "next" url.
            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not login_scheme or login_scheme == current_scheme) and
                    (not login_netloc or login_netloc == current_netloc)):
                path = request.get_full_path()
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(
                path, resolved_login_url, redirect_field_name)
        return _wrapped_view
    return decorator