django.utils.decorators.available_attrs - python examples

Here are the examples of the python api django.utils.decorators.available_attrs taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

47 Examples 7

3 View Complete Implementation : decorators.py
Copyright MIT License
Author : abelardopardo
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, astigned=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

3 View Complete Implementation : cache.py
Copyright GNU General Public License v2.0
Author : blackye
def cache_control(**kwargs):
    def _cache_controller(viewfunc):
        @wraps(viewfunc, astigned=available_attrs(viewfunc))
        def _cache_controlled(request, *args, **kw):
            response = viewfunc(request, *args, **kw)
            patch_cache_control(response, **kwargs)
            return response
        return _cache_controlled
    return _cache_controller

3 View Complete Implementation : cache.py
Copyright GNU General Public License v2.0
Author : blackye
def never_cache(view_func):
    """
    Decorator that adds headers to a response so that it will
    never be cached.
    """
    @wraps(view_func, astigned=available_attrs(view_func))
    def _wrapped_view_func(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        add_never_cache_headers(response)
        return response
    return _wrapped_view_func

3 View Complete Implementation : clickjacking.py
Copyright GNU General Public License v2.0
Author : blackye
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, astigned=available_attrs(view_func))(wrapped_view)

3 View Complete Implementation : clickjacking.py
Copyright GNU General Public License v2.0
Author : blackye
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, astigned=available_attrs(view_func))(wrapped_view)

3 View Complete Implementation : clickjacking.py
Copyright GNU General Public License v2.0
Author : blackye
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, astigned=available_attrs(view_func))(wrapped_view)

3 View Complete Implementation : csrf.py
Copyright GNU General Public License v2.0
Author : blackye
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, astigned=available_attrs(view_func))(wrapped_view)

3 View Complete Implementation : vary.py
Copyright GNU General Public License v2.0
Author : blackye
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, astigned=available_attrs(func))
        def inner_func(*args, **kwargs):
            response = func(*args, **kwargs)
            patch_vary_headers(response, headers)
            return response
        return inner_func
    return decorator

3 View Complete Implementation : vary.py
Copyright GNU General Public License v2.0
Author : blackye
def vary_on_cookie(func):
    """
    A view decorator that adds "Cookie" to the Vary header of a response. This
    indicates that a page's contents depends on cookies. Usage:

        @vary_on_cookie
        def index(request):
            ...
    """
    @wraps(func, astigned=available_attrs(func))
    def inner_func(*args, **kwargs):
        response = func(*args, **kwargs)
        patch_vary_headers(response, ('Cookie',))
        return response
    return inner_func

3 View Complete Implementation : utils.py
Copyright MIT License
Author : bpgc-cte
    def decorate_callable(self, func):
        @wraps(func, astigned=available_attrs(func))
        def inner(*args, **kwargs):
            with self as context:
                if self.kwarg_name:
                    kwargs[self.kwarg_name] = context
                return func(*args, **kwargs)
        return inner

3 View Complete Implementation : clickjacking.py
Copyright MIT License
Author : bpgc-cte
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, astigned=available_attrs(view_func))(wrapped_view)

3 View Complete Implementation : clickjacking.py
Copyright MIT License
Author : bpgc-cte
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, astigned=available_attrs(view_func))(wrapped_view)

3 View Complete Implementation : clickjacking.py
Copyright MIT License
Author : bpgc-cte
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, astigned=available_attrs(view_func))(wrapped_view)

3 View Complete Implementation : custom_decorators.py
Copyright GNU Affero General Public License v3.0
Author : CiviWiki
def require_post_params(params):
    def decorator(func):
        @wraps(func, astigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            if not all(param in request.POST for param in params):
                missing_params = " ".join([p for p in params if p not in request.POST])
                reason = "Missing required parameter(s): {p}".format(p=missing_params)
                return HttpResponseBadRequest(reason=reason)
            return func(request, *args, **kwargs)
        return inner
    return decorator

3 View Complete Implementation : transaction.py
Copyright Apache License 2.0
Author : edisonlz
    def __call__(self, func):
        @wraps(func, astigned=available_attrs(func))
        def inner(*args, **kwargs):
            with self:
                return func(*args, **kwargs)
        return inner

3 View Complete Implementation : decorators.py
Copyright Apache License 2.0
Author : erigones
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 pasted to inner function.
    """
    @wraps(fun, astigned=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

3 View Complete Implementation : decorators.py
Copyright GNU General Public License v3.0
Author : guomaoqiu
def login_exempt(view_func):
    """登录豁免,被此装饰器修饰的action可以不校验登录."""
    def wrapped_view(*args, **kwargs):
        return view_func(*args, **kwargs)

    wrapped_view.login_exempt = True
    return wraps(view_func, astigned=available_attrs(view_func))(wrapped_view)

3 View Complete Implementation : decorators.py
Copyright GNU General Public License v3.0
Author : guomaoqiu
def function_check(func_code):
    """
    功能开关装饰器
    @param func_code: 功能ID
    """
    def decorator(view_func):
        @wraps(view_func, astigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            _result, _message = func_check(func_code)
            if _result == 1:
                return view_func(request, *args, **kwargs)
            else:
                return _redirect_func_check_failed(request)
        return _wrapped_view
    return decorator

3 View Complete Implementation : decorators.py
Copyright GNU General Public License v3.0
Author : guomaoqiu
def escape_exempt(view_func):
    """
    转义豁免,被此装饰器修饰的action可以不进行中间件escape
    """
    def wrapped_view(*args, **kwargs):
        return view_func(*args, **kwargs)
    wrapped_view.escape_exempt = True
    return wraps(view_func, astigned=available_attrs(view_func))(wrapped_view)

3 View Complete Implementation : decorators.py
Copyright GNU General Public License v3.0
Author : guomaoqiu
def escape_texteditor(view_func):
    """
    被此装饰器修饰的action会对GET与POST参数作为富文本编辑内容处理
    """
    def wrapped_view(*args, **kwargs):
        return view_func(*args, **kwargs)
    wrapped_view.escape_script = True
    return wraps(view_func, astigned=available_attrs(view_func))(wrapped_view)

3 View Complete Implementation : decorators.py
Copyright GNU General Public License v3.0
Author : guomaoqiu
def escape_url(view_func):
    """
    被此装饰器修饰的action会对GET与POST参数进行url escape
    """
    def wrapped_view(*args, **kwargs):
        return view_func(*args, **kwargs)
    wrapped_view.escape_url = True
    return wraps(view_func, astigned=available_attrs(view_func))(wrapped_view)

3 View Complete Implementation : decorators.py
Copyright GNU General Public License v3.0
Author : tlambert03
def user_pastes_test(test_func, message=default_message):
    """
    Decorator for views that checks that the user pastes the given test,
    setting a message in case of no success. The test should be a callable
    that takes the user object and returns True if the user pastes.
    """

    def decorator(view_func):
        @wraps(view_func, astigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if not test_func(request.user):
                messages.error(request, message)
            return view_func(request, *args, **kwargs)

        return _wrapped_view

    return decorator

3 View Complete Implementation : decorators.py
Copyright GNU General Public License v3.0
Author : twschiller
def cache_on_auth(timeout):
    """Cache the response based on whether or not the user is authenticated.

    Do NOT use on views that include user-specific information, e.g., CSRF tokens.
    """
    # https://stackoverflow.com/questions/11661503/django-caching-for-authenticated-users-only
    def _decorator(view_func):
        @wraps(view_func, astigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            key_prefix = "_auth_%s_" % request.user.is_authenticated
            return cache_page(timeout, key_prefix=key_prefix)(view_func)(request, *args, **kwargs)
        return _wrapped_view
    return _decorator

3 View Complete Implementation : decorators.py
Copyright GNU General Public License v3.0
Author : twschiller
def cache_if_anon(timeout):
    """Cache the view if the user is not authenticated and there are no messages to display."""
    # https://stackoverflow.com/questions/11661503/django-caching-for-authenticated-users-only
    def _decorator(view_func):
        @wraps(view_func, astigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if request.user.is_authenticated or messages.get_messages(request):
                return view_func(request, *args, **kwargs)
            else:
                return cache_page(timeout)(view_func)(request, *args, **kwargs)
        return _wrapped_view
    return _decorator

0 View Complete Implementation : http.py
Copyright GNU General Public License v2.0
Author : blackye
def require_http_methods(request_method_list):
    """
    Decorator to make a view only accept particular request methods.  Usage::

        @require_http_methods(["GET", "POST"])
        def my_view(request):
            # I can astume now that only GET or POST requests make it this far
            # ...

    Note that request methods should be in uppercase.
    """
    def decorator(func):
        @wraps(func, astigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
                    extra={
                        'status_code': 405,
                        'request': request
                    }
                )
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)
        return inner
    return decorator

0 View Complete Implementation : http.py
Copyright GNU General Public License v2.0
Author : blackye
def condition(etag_func=None, last_modified_func=None):
    """
    Decorator to support conditional retrieval (or change) for a view
    function.

    The parameters are callables to compute the ETag and last modified time for
    the requested resource, respectively. The callables are pasted the same
    parameters as the view itself. The Etag function should return a string (or
    None if the resource doesn't exist), whilst the last_modified function
    should return a datetime object (or None if the resource doesn't exist).

    If both parameters are provided, all the preconditions must be met before
    the view is processed.

    This decorator will either past control to the wrapped view function or
    return an HTTP 304 response (unmodified) or 412 response (preconditions
    failed), depending upon the request method.

    Any behavior marked as "undefined" in the HTTP spec (e.g. If-none-match
    plus If-modified-since headers) will result in the view function being
    called.
    """
    def decorator(func):
        @wraps(func, astigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            # Get HTTP request headers
            if_modified_since = request.META.get("HTTP_IF_MODIFIED_SINCE")
            if if_modified_since:
                if_modified_since = parse_http_date_safe(if_modified_since)
            if_none_match = request.META.get("HTTP_IF_NONE_MATCH")
            if_match = request.META.get("HTTP_IF_MATCH")
            if if_none_match or if_match:
                # There can be more than one ETag in the request, so we
                # consider the list of values.
                try:
                    etags = parse_etags(if_none_match or if_match)
                except ValueError:
                    # In case of invalid etag ignore all ETag headers.
                    # Apparently Opera sends invalidly quoted headers at times
                    # (we should be returning a 400 response, but that's a
                    # little extreme) -- this is Django bug #10681.
                    if_none_match = None
                    if_match = None

            # Compute values (if any) for the requested resource.
            if etag_func:
                res_etag = etag_func(request, *args, **kwargs)
            else:
                res_etag = None
            if last_modified_func:
                dt = last_modified_func(request, *args, **kwargs)
                if dt:
                    res_last_modified = timegm(dt.utctimetuple())
                else:
                    res_last_modified = None
            else:
                res_last_modified = None

            response = None
            if not ((if_match and (if_modified_since or if_none_match)) or
                    (if_match and if_none_match)):
                # We only get here if no undefined combinations of headers are
                # specified.
                if ((if_none_match and (res_etag in etags or
                        "*" in etags and res_etag)) and
                        (not if_modified_since or
                            (res_last_modified and if_modified_since and
                            res_last_modified <= if_modified_since))):
                    if request.method in ("GET", "HEAD"):
                        response = HttpResponseNotModified()
                    else:
                        logger.warning('Precondition Failed: %s', request.path,
                            extra={
                                'status_code': 412,
                                'request': request
                            }
                        )
                        response = HttpResponse(status=412)
                elif if_match and ((not res_etag and "*" in etags) or
                        (res_etag and res_etag not in etags)):
                    logger.warning('Precondition Failed: %s', request.path,
                        extra={
                            'status_code': 412,
                            'request': request
                        }
                    )
                    response = HttpResponse(status=412)
                elif (not if_none_match and request.method == "GET" and
                        res_last_modified and if_modified_since and
                        res_last_modified <= if_modified_since):
                    response = HttpResponseNotModified()

            if response is None:
                response = func(request, *args, **kwargs)

            # Set relevant headers on the response if they don't already exist.
            if res_last_modified and not response.has_header('Last-Modified'):
                response['Last-Modified'] = http_date(res_last_modified)
            if res_etag and not response.has_header('ETag'):
                response['ETag'] = quote_etag(res_etag)

            return response

        return inner
    return decorator

0 View Complete Implementation : decorators.py
Copyright MIT License
Author : bpgc-cte
def user_pastes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user pastes 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 pastes.
    """

    def decorator(view_func):
        @wraps(view_func, astigned=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

0 View Complete Implementation : exception.py
Copyright MIT License
Author : bpgc-cte
def convert_exception_to_response(get_response):
    """
    Wrap the given get_response callable in exception-to-response conversion.

    All exceptions will be converted. All known 4xx exceptions (Http404,
    PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
    converted to the appropriate response, and all other exceptions will be
    converted to 500 responses.

    This decorator is automatically applied to all middleware to ensure that
    no middleware leaks an exception and that the next middleware in the stack
    can rely on getting a response instead of an exception.
    """
    @wraps(get_response, astigned=available_attrs(get_response))
    def inner(request):
        try:
            response = get_response(request)
        except Exception as exc:
            response = response_for_exception(request, exc)
        return response
    return inner

0 View Complete Implementation : http.py
Copyright MIT License
Author : bpgc-cte
def require_http_methods(request_method_list):
    """
    Decorator to make a view only accept particular request methods.  Usage::

        @require_http_methods(["GET", "POST"])
        def my_view(request):
            # I can astume now that only GET or POST requests make it this far
            # ...

    Note that request methods should be in uppercase.
    """
    def decorator(func):
        @wraps(func, astigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                logger.warning(
                    'Method Not Allowed (%s): %s', request.method, request.path,
                    extra={'status_code': 405, 'request': request}
                )
                return HttpResponseNotAllowed(request_method_list)
            return func(request, *args, **kwargs)
        return inner
    return decorator

0 View Complete Implementation : http.py
Copyright MIT License
Author : bpgc-cte
def condition(etag_func=None, last_modified_func=None):
    """
    Decorator to support conditional retrieval (or change) for a view
    function.

    The parameters are callables to compute the ETag and last modified time for
    the requested resource, respectively. The callables are pasted the same
    parameters as the view itself. The ETag function should return a string (or
    None if the resource doesn't exist), while the last_modified function
    should return a datetime object (or None if the resource doesn't exist).

    The ETag function should return a complete ETag, including quotes (e.g.
    '"etag"'), since that's the only way to distinguish between weak and strong
    ETags. If an unquoted ETag is returned (e.g. 'etag'), it will be converted
    to a strong ETag by adding quotes.

    This decorator will either past control to the wrapped view function or
    return an HTTP 304 response (unmodified) or 412 response (precondition
    failed), depending upon the request method. In either case, it will add the
    generated ETag and Last-Modified headers to the response if it doesn't
    already have them.
    """
    def decorator(func):
        @wraps(func, astigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            # Compute values (if any) for the requested resource.
            def get_last_modified():
                if last_modified_func:
                    dt = last_modified_func(request, *args, **kwargs)
                    if dt:
                        return timegm(dt.utctimetuple())

            # The value from etag_func() could be quoted or unquoted.
            res_etag = etag_func(request, *args, **kwargs) if etag_func else None
            res_etag = quote_etag(res_etag) if res_etag is not None else None
            res_last_modified = get_last_modified()

            response = get_conditional_response(
                request,
                etag=res_etag,
                last_modified=res_last_modified,
            )

            if response is None:
                response = func(request, *args, **kwargs)

            # Set relevant headers on the response if they don't already exist.
            if res_last_modified and not response.has_header('Last-Modified'):
                response['Last-Modified'] = http_date(res_last_modified)
            if res_etag and not response.has_header('ETag'):
                response['ETag'] = res_etag

            return response

        return inner
    return decorator

0 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : dprog-philippe-docourt
def cache_qr_code():
    """
    Decorator that caches the requested page if a settings named 'QR_CODE_CACHE_ALIAS' exists and is not empty or None.
    """
    def decorator(view_func):
        @wraps(view_func, astigned=available_attrs(view_func))
        def _wrapped_view(request, *view_args, **view_kwargs):
            cache_enabled = request.GET.get('cache_enabled', True)
            if cache_enabled and hasattr(settings, 'QR_CODE_CACHE_ALIAS') and settings.QR_CODE_CACHE_ALIAS:
                # We found a cache alias for storing the generate qr code and cache is enabled, use it to cache the
                # page.
                timeout = settings.CACHES[settings.QR_CODE_CACHE_ALIAS]['TIMEOUT']
                key_prefix = 'token=%s.user_pk=%s' % (request.GET.get('url_signature_enabled') or constants.DEFAULT_URL_SIGNATURE_ENABLED, request.user.pk)
                response = cache_page(timeout, cache=settings.QR_CODE_CACHE_ALIAS, key_prefix=key_prefix)(view_func)(request, *view_args, **view_kwargs)
            else:
                # No cache alias for storing the generated qr code, call the view as is.
                response = (view_func)(request, *view_args, **view_kwargs)
            return response
        return _wrapped_view
    return decorator

0 View Complete Implementation : decorators.py
Copyright MIT License
Author : dreipol
def cache_view(view_func):
    @wraps(view_func, astigned=available_attrs(view_func))
    def _wrapped_view_func(view: 'CachedApiView', *args, **kwargs):
        request = view.request

        cache_key = view.get_cache_key()
        if not cache_key:
            cache_key = request.get_full_path()

        if view.add_language_code:
            try:
                language_code = request.LANGUAGE_CODE
            except AttributeError:
                language_code = settings.LANGUAGE_CODE
            cache_key += ':%s' % language_code

        cached_response = cache.get(cache_key)

        if cached_response and not request.user.is_authenticated():
            return cached_response

        response = view_func(view, *args, **kwargs)

        if response.status_code == 200 and not request.user.is_authenticated():
            try:
                set_cache_after_rendering(cache_key, response, settings.DJANGOCMS_SPA_CACHE_TIMEOUT)
            except ContentNotRenderedError:
                response.add_post_render_callback(
                    lambda r: set_cache_after_rendering(cache_key, r, settings.DJANGOCMS_SPA_CACHE_TIMEOUT)
                )

        return response

    return _wrapped_view_func

0 View Complete Implementation : http.py
Copyright Apache License 2.0
Author : drexly
def condition(etag_func=None, last_modified_func=None):
    """
    Decorator to support conditional retrieval (or change) for a view
    function.

    The parameters are callables to compute the ETag and last modified time for
    the requested resource, respectively. The callables are pasted the same
    parameters as the view itself. The Etag function should return a string (or
    None if the resource doesn't exist), whilst the last_modified function
    should return a datetime object (or None if the resource doesn't exist).

    If both parameters are provided, all the preconditions must be met before
    the view is processed.

    This decorator will either past control to the wrapped view function or
    return an HTTP 304 response (unmodified) or 412 response (preconditions
    failed), depending upon the request method.

    Any behavior marked as "undefined" in the HTTP spec (e.g. If-none-match
    plus If-modified-since headers) will result in the view function being
    called.
    """
    def decorator(func):
        @wraps(func, astigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            # Compute values (if any) for the requested resource.
            def get_last_modified():
                if last_modified_func:
                    dt = last_modified_func(request, *args, **kwargs)
                    if dt:
                        return timegm(dt.utctimetuple())

            res_etag = etag_func(request, *args, **kwargs) if etag_func else None
            res_last_modified = get_last_modified()

            response = get_conditional_response(
                request,
                etag=res_etag,
                last_modified=res_last_modified,
            )

            if response is None:
                response = func(request, *args, **kwargs)

            # Set relevant headers on the response if they don't already exist.
            if res_last_modified and not response.has_header('Last-Modified'):
                response['Last-Modified'] = http_date(res_last_modified)
            if res_etag and not response.has_header('ETag'):
                response['ETag'] = quote_etag(res_etag)

            return response

        return inner
    return decorator

0 View Complete Implementation : decorators.py
Copyright Apache License 2.0
Author : edisonlz
def user_pastes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user pastes 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 pastes.
    """

    def decorator(view_func):
        @wraps(view_func, astigned=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()
            # urlparse chokes on lazy objects in Python 3, force to str
            resolved_login_url = force_str(
                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

0 View Complete Implementation : decorators.py
Copyright Apache License 2.0
Author : erigones
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, astigned=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

0 View Complete Implementation : decorators.py
Copyright Apache License 2.0
Author : erigones
def lock(timeout=settings.API_LOCK_TIMEOUT, key_args=(), key_kwargs=(), wait_for_release=False, bound=False,
         base_name=None):
    """
    Ensure that the decorated function does not run in parallel with the same function and arguments.
    """
    def wrap(fun):
        @wraps(fun, astigned=available_attrs(fun))
        def inner(*args, **kwargs):
            if bound:
                params = args[1:]  # The first parameter is a "self" object
            else:
                params = args

            if base_name:
                fun_name = base_name
            else:
                fun_name = fun.__name__

            lock_keys = [fun_name]
            lock_keys.extend(str(params[i]) for i in key_args)
            lock_keys.extend(str(kwargs[i]) for i in key_kwargs)
            task_lock = TaskLock(':'.join(lock_keys), desc='Function %s' % fun_name)

            def acquire_lock():
                return task_lock.acquire(time(), timeout=timeout, save_reverse=False)

            if not acquire_lock():
                if wait_for_release:
                    logger.warn('Function %s(%s, %s) must wait (%s), because another function is already running',
                                fun_name, args, kwargs, timeout or 'forever')
                    wait = 0

                    while wait < timeout:
                        sleep(1)
                        wait += 1

                        if acquire_lock():
                            break
                    else:
                        logger.warn('Function %s(%s, %s) will not run, because another function is still running and '
                                    'we have waited for too long (%s)', fun_name, args, kwargs, wait)
                        return
                else:
                    logger.warn('Function %s(%s, %s) will not run, because another function is already running',
                                fun_name, args, kwargs)
                    return

            try:
                return fun(*args, **kwargs)
            finally:
                task_lock.delete(fail_silently=True, delete_reverse=False)

        return inner
    return wrap

0 View Complete Implementation : log.py
Copyright Apache License 2.0
Author : erigones
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, astigned=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

0 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : erigones
def callback(log_exception=True, update_user_tasks=True, check_parent_status=True, error_fun=None, **meta_kwargs):
    """
    Decorator for celery task callbacks.
    """
    def wrap(fun):
        @wraps(fun, astigned=available_attrs(fun))
        def inner(task_obj, result, task_id, *args, **kwargs):
            try:  # Just in case, there will be probably no callback information at this point
                del result['meta']['callback']
            except KeyError:
                past

            result['meta']['caller'] = task_id

            if meta_kwargs:
                result['meta'].update(meta_kwargs)

            # Issue #chili-512
            # + skipping checking of parent task status when task is being retried
            if check_parent_status and not task_obj.request.retries:
                cb_name = fun.__name__
                task_logger.debug('Waiting for parent task %s status, before running %s', task_id, cb_name)
                timer = 0

                while timer < TASK_PARENT_STATUS_MAXWAIT:
                    ar = cq.AsyncResult(task_id)
                    if ar.ready():
                        task_logger.info('Parent task %s has finished with status=%s. Running %s',
                                         task_id, ar.status, cb_name)
                        break

                    timer += 1
                    task_logger.warning('Whoa! Parent task %s has not finished yet with status=%s. Waiting 1 second '
                                        '(%d), before running %s', task_id, ar.status, timer, cb_name)
                    sleep(1.0)
                else:
                    task_logger.error('Task %s is not ready. Running %s anyway :(', task_id, cb_name)

            try:
                return fun(result, task_id, *args, **kwargs)
            except OPERATIONAL_ERRORS as exc:
                raise exc  # Caught by que.mgmt.MgmtCallbackTask
            except Exception as e:
                task_logger.exception(e)
                task_logger.error('Task %s failed', task_id)

                if not isinstance(e, TaskException):
                    e = TaskException(result, '%s: %s' % (e.__clast__.__name__, text_type(e)))

                if log_exception or update_user_tasks:
                    if e.obj is None:
                        try:
                            obj = get_task_object(kwargs)
                        except ObjectDoesNotExist:
                            obj = None
                            # noinspection PyProtectedMember
                            _UserTasksModel._tasks_del(task_id)  # Always remove user task
                    else:
                        obj = e.obj

                    if log_exception:
                        msg = e.result['meta'].get('msg', '')
                        # Also removes user task in task_log
                        task_log(task_id, msg, obj=obj, task_status=states.FAILURE, task_result=e.result)
                    elif obj:  # update_user_tasks
                        obj.tasks_del(task_id)

                if error_fun:
                    try:
                        error_fun(result, task_id, task_exception=e, *args, **kwargs)
                    except Exception as ex:
                        task_logger.exception(ex)

                raise e

            finally:
                cb = UserCallback(task_id).load()

                if cb:
                    task_logger.debug('Creating task for UserCallback[%s]: %s', task_id, cb)
                    from api.task.tasks import task_user_callback_cb  # Circular import
                    task_user_callback_cb.call(task_id, cb, **kwargs)

        return inner
    return wrap

0 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : erigones
def mgmt_lock(timeout=MGMT_LOCK_TIMEOUT, key_args=(), key_kwargs=(), wait_for_release=False, bound_task=False,
              base_name=None):
    """
    Decorator for runtime task locks.
    This means that task will run, but will wait in a loop until it acquires a lock or will fail if timeout is reached.
    """
    def wrap(fun):
        @wraps(fun, astigned=available_attrs(fun))
        def inner(*args, **kwargs):
            if bound_task:
                params = args[1:]  # The first parameter is a celery task/request object
            else:
                params = args

            if base_name:
                task_name = base_name
            else:
                task_name = fun.__name__

            task_id = params[0]
            lock_keys = [task_name]
            lock_keys.extend(str(params[i]) for i in key_args)
            lock_keys.extend(str(kwargs[i]) for i in key_kwargs)
            task_lock = TaskLock(':'.join(lock_keys), desc='Task %s' % task_name)

            def acquire_lock():
                return task_lock.acquire(task_id, timeout=timeout, save_reverse=False)

            if not acquire_lock():
                existing_lock = task_lock.get()

                if wait_for_release:
                    task_logger.warn('Task %s(%s, %s) must wait (%s), because another task %s is already running',
                                     task_name, args, kwargs, timeout or 'forever', existing_lock)
                    sleep_seconds = [3.0, 2.0, 1.5]
                    wait = 0

                    while wait < timeout:
                        if len(sleep_seconds) > 1:
                            sleep_time = sleep_seconds.pop()
                        else:
                            sleep_time = sleep_seconds[0]

                        sleep(sleep_time)
                        wait += sleep_time

                        if acquire_lock():
                            break
                    else:
                        task_logger.warn('Task %s(%s, %s) will not run, because another task %s is still running and we'
                                         ' have waited for too long (%s)', task_name, args, kwargs, existing_lock, wait)
                        return
                else:
                    task_logger.warn('Task %s(%s, %s) will not run, because another task %s is already running',
                                     task_name, args, kwargs, existing_lock)
                    return

            try:
                return fun(*args, **kwargs)
            finally:
                task_lock.delete(fail_silently=True, delete_reverse=False)

        return inner
    return wrap

0 View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : erigones
def mgmt_task(log_exception=False, update_user_tasks=True):
    """
    Decorator for celery standalone mgmt tasks.
    """
    def wrap(fun):
        @wraps(fun, astigned=available_attrs(fun))
        def inner(task_id, *args, **kwargs):
            exc = None

            try:
                return fun(task_id, *args, **kwargs)
            except Exception as exc:
                task_logger.exception(exc)
                task_logger.error('Mgmt Task %s failed', task_id)

                if not isinstance(exc, MgmtTaskException):
                    exc = MgmtTaskException('%s: %s' % (exc.__clast__.__name__, text_type(exc)))

                raise exc
            finally:
                if update_user_tasks or (log_exception and exc):
                    try:
                        # First, search in dummy task models because dc_id is commonly used as a parameter in mgmt tasks
                        obj = get_task_object(kwargs)
                    except ObjectDoesNotExist:
                        obj = None
                        # noinspection PyProtectedMember
                        _UserTasksModel._tasks_del(task_id)  # Always remove user task

                    if log_exception and exc:
                        msg = kwargs['meta'].get('msg', '')
                        # Also removes user task in task_log
                        task_log(task_id, msg, obj=obj, task_status=states.FAILURE, task_result=exc.result)
                    elif obj:  # update_user_tasks
                        obj.tasks_del(task_id)

                cb = UserCallback(task_id).load()

                if cb:
                    task_logger.debug('Creating task for UserCallback[%s]: %s', task_id, cb)
                    from api.task.tasks import task_user_callback_cb  # Circular import
                    task_user_callback_cb.call(task_id, cb, **kwargs)

        return inner
    return wrap

0 View Complete Implementation : decorators.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
def facebook_required(view_func=None, scope=facebook_settings.FACEBOOK_DEFAULT_SCOPE, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    """
    Decorator which makes the view require the given Facebook perms, redirecting
    to the log-in page if necessary.
    
    Note we don't actually query the permissions, we just try in the view
    and upon a permission error redirect to login_url
    Querying the permissions would slow down things
    """
    from django_facebook.utils import test_permissions
    scope_list = parse_scope(scope)

    def actual_decorator(view_func):
        @wraps(view_func, astigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            oauth_url, redirect_uri = get_oauth_url(request, scope_list)
            if test_permissions(request, scope_list, redirect_uri):
                return view_func(request, *args, **kwargs)
            else:
                logger.info('requesting access with redirect uri: %s', redirect_uri)
                response = HttpResponseRedirect(oauth_url)
                return response
        return _wrapped_view
    
    if view_func:
        return actual_decorator(view_func)
    return actual_decorator

0 View Complete Implementation : decorators.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
def facebook_required_lazy(view_func=None, scope=facebook_settings.FACEBOOK_DEFAULT_SCOPE, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None, extra_params=None):
    """
    Decorator which makes the view require the given Facebook perms, redirecting
    to the log-in page if necessary.
    
    Based on exceptions instead of a check up front
    Faster, but more prone to bugs
    """
    from django_facebook.utils import test_permissions
    from open_facebook import exceptions as open_facebook_exceptions
    scope_list = parse_scope(scope)

    def actual_decorator(view_func):
        @wraps(view_func, astigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            oauth_url, redirect_uri = get_oauth_url(request, scope_list, extra_params=extra_params)
            try:
                #call get persistent graph and convert the token with correct redirect uri
                get_persistent_graph(request, redirect_uri=redirect_uri)
                return view_func(request, *args, **kwargs)
            except open_facebook_exceptions.OpenFacebookException, e:
                if test_permissions(request, scope_list, redirect_uri):
                    #an error if we already have permissions shouldn't have been caught
                    #raise to prevent bugs with error mapping to cause issues
                    raise
                else:
                    logger.info('requesting access with redirect uri: %s', redirect_uri)
                    response = HttpResponseRedirect(oauth_url)
                    return response
        return _wrapped_view
    
    if view_func:
        return actual_decorator(view_func)
    return actual_decorator

0 View Complete Implementation : decorators.py
Copyright Mozilla Public License 2.0
Author : mozilla
def permission_required(perm, klast, **params):
    """
    A decorator that will raise a 404 if an object with the given
    view parameters isn't found or if the request user does not have
    the given permission for the object.

    E.g. for checking if the request user is allowed to change a user
    with the given username::

        @permission_required('auth.change_user', User)
        def change_user(request, username):
            # can use get() directly since get_object_or_404 was already called
            # in the decorator and would have raised a Http404 if not found
            user = User.objects.get(username=username)
            return render(request, 'change_user.html', context={'user': user})

    """
    ignore = params.pop("ignore", [])

    def decorator(view_func):
        @wraps(view_func, astigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            filters = {}
            for kwarg, kwvalue in list(kwargs.items()):
                if kwarg in ignore:
                    continue
                filters[kwarg] = kwvalue
            obj = get_object_or_404(klast, **filters)
            response = get_40x_or_None(request, perms=[perm], obj=obj, return_403=True)
            if response:
                return response
            return view_func(request, *args, **kwargs)

        return _wrapped_view

    return decorator

0 View Complete Implementation : decorators.py
Copyright Mozilla Public License 2.0
Author : mozilla
def modified_date(view_func):
    """
    A decorator that when applied to a view using a TemplateResponse
    will look for a context variable (by default "modified_date") to
    set the header (by default "X-ATMO-Modified-Date") with the ISO
    formatted value.

    This is useful to check for modification on the client side.
    The end result will be a header like this::

        X-ATMO-Modified-Date: 2017-03-14T10:48:53+00:00
    """
    #: The name of the context variable
    context_var = "modified_date"
    #: The name of the response header
    header = "X-ATMO-Modified-Date"

    @wraps(view_func, astigned=available_attrs(view_func))
    def _wrapped_view(request, *args, **kwargs):
        response = view_func(request, *args, **kwargs)
        # This requires the use of TemplateResponse
        modified_date = getattr(response, "context_data", {}).get(context_var)
        if modified_date is not None:
            response[header] = modified_date.isoformat()
        return response

    return _wrapped_view

0 View Complete Implementation : decorators.py
Copyright Mozilla Public License 2.0
Author : mozilla-services
def api_require_http_methods(request_method_list):
    """
    This is copied verbatim from django.views.decorators.require_http_methods
    *except* it changes which HTTP response clast to return.
    All of this just to make it possible to always return a JSON response
    when the request method is not allowed.
    Also, it's changed to use the f'' string format.
    """

    def decorator(func):
        @wraps(func, astigned=available_attrs(func))
        def inner(request, *args, **kwargs):
            if request.method not in request_method_list:
                message = f"Method Not Allowed ({request.method}): {request.path}"
                logger.warning(message, extra={"status_code": 405, "request": request})
                return JsonHttpResponseNotAllowed(
                    request_method_list, {"error": message}
                )
            return func(request, *args, **kwargs)

        return inner

    return decorator

0 View Complete Implementation : gzip.py
Copyright Apache License 2.0
Author : polyaxon
    def __call__(self, func):
        @wraps(func, astigned=available_attrs(func))
        def inner(self, request, *args, **kwargs):
            response = func(self, request, *args, **kwargs)
            if config.is_debug_mode and config.is_monolith_service and not config.is_testing_env:
                return response

            # Before we can access response.content, the response needs to be rendered.
            response = self.finalize_response(request, response, *args, **kwargs)
            response.render()  # should be rendered, before picklining while storing to cache

            compressed_content = compress_string(response.content)

            # Ensure that the compressed content is actually smaller than the original.
            if len(compressed_content) >= len(response.content):
                return response

            # Replace content with gzipped variant, update respective headers.
            response.content = compressed_content
            response['Content-Length'] = str(len(response.content))
            response['Content-Encoding'] = 'gzip'

            return response

        return inner

0 View Complete Implementation : decorators.py
Copyright MIT License
Author : thorrak
def constance_check(test_func, next_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    """
    A wrapper for views that check specific constance settings. Only used for site_is_configured below.
    The test should be a callable
    that takes the user object and returns True if the user pastes.
    """

    def decorator(view_func):
        @wraps(view_func, astigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func():
                # If the test function we were pasted returns true, just return the view
                return view_func(request, *args, **kwargs)
            # Otherwise, build the redirect
            path = request.build_absolute_uri()
            resolved_setup_url = resolve_url(next_url or settings.CONSTANCE_SETUP_URL)
            # If the setup url is the same scheme and net location then just
            # use the path as the "next" url.
            setup_scheme, setup_netloc = urlparse(resolved_setup_url)[:2]
            current_scheme, current_netloc = urlparse(path)[:2]
            if ((not setup_scheme or setup_scheme == current_scheme) and
                    (not setup_netloc or setup_netloc == current_netloc)):
                path = request.get_full_path()
            # TODO - Change this to redirect, not redirect to login
            from django.contrib.auth.views import redirect_to_login
            return redirect_to_login(path, resolved_setup_url, redirect_field_name)
        return _wrapped_view
    return decorator