A Django view decorator that will add the `X-Clacks-Overhead` header.

    Usage:

        @clacks_overhead
        def my_view(request):
            return my_response
331361
def clacks_overhead(fn):
    
    @wraps(fn)
    def _wrapped(*args, **kw):
        response = fn(*args, **kw)
        response['X-Clacks-Overhead'] = 'GNU Terry Pratchett'
        return response

    return _wrapped
1201208
def view(self, *args, **kwargs):
        
        def decorator(f):
            kwargs.setdefault("view_class", self.view_class)
            return self.add_view(as_view(*args, **kwargs)(f))
        return decorator
829820
def mock_decorator(*a, **k):
    
    # This is a decorator without parameters, e.g.
    #
    # @login_required
    # def some_view(request):
    #     ...
    #
    if a:
        # This could fail in the instance where a callable argument is passed
        # as a parameter to the decorator!
        if callable(a[0]):
            def wrapper(*args, **kwargs):
                return a[0](*args, **kwargs)
            return wrapper

    # This is a decorator with parameters, e.g.
    #
    # @render_template("index.html")
    # def some_view(request):
    #     ...
    #
    def real_decorator(function):
        def wrapper(*args, **kwargs):
            return function(*args, **kwargs)
        return wrapper
    return real_decorator
956297
def json(func):
    
    if inspect.isclass(func):
        apply_function_to_members(func, json)
        return func
    else:
        @functools.wraps(func)
        def decorated_view(*args, **kwargs):
            data = func(*args, **kwargs)
            return _build_response(data, jsonify)
        return decorated_view
106065
def outbox(request, template_name='django_messages/outbox.html'):
    
    message_list = Message.objects.outbox_for(request.user)
    return render(request, template_name, {
        'message_list': message_list,
    })
943373
def maintenance_view(template=None):
    
    if not template:
        template = "Pylot/Maintenance/index.html"

    class Maintenance(Pylot):
        @classmethod
        def register(cls, app, **kwargs):
            super(cls, cls).register(app, **kwargs)

            if cls.config_("MAINTENANCE_ON"):
                @app.before_request
                def on_maintenance():
                    return cls.render(layout=template), 503
    return Maintenance
1127715
def log_view(func):
    

    @functools.wraps(func)
    def view_logger(*args, **kwargs):
        log.debug("call view %r", func.__name__)
        try:
            response = func(*args, **kwargs)
        except Exception as err:
            log.error("view exception: %s", err)
            traceback.print_exc(file=sys.stderr)
            raise

        log.debug("Response: %s", response)
        return response

    return view_logger
878793
def make_proxy_method(cls, name):
        

        i = cls()
        view = getattr(i, name)

        for decorator in cls.decorators:
            view = decorator(view)

        @functools.wraps(view)
        def proxy(**forgettable_view_args):
            # Always use the global request object's view_args, because they
            # can be modified by intervening function before an endpoint or
            # wrapper gets called. This matches Flask's behavior.
            del forgettable_view_args

            if hasattr(i, "before_request"):
                response = i.before_request(name, **request.view_args)
                if response is not None:
                    return response

            before_view_name = "before_" + name
            if hasattr(i, before_view_name):
                before_view = getattr(i, before_view_name)
                response = before_view(**request.view_args)
                if response is not None:
                    return response

            response = view(**request.view_args)

            # You can also return a dict or None, it will pass it to render
            if isinstance(response, dict) or response is None:
                response = response or {}
                if hasattr(i, "_renderer"):
                    response = i._renderer(response)
                else:
                    _template = build_endpoint_route_name(cls, view.__name__)
                    _template = utils.list_replace([".", ":"], "/", _template)
                    _template = "%s.%s" % (_template, cls.template_markup)

                    # Set the title from the nav title, if not set
                    _meta_title = getattr(g, "__META__", {}).get("title")
                    if (not _meta_title or _meta_title == "") and get_view_attr(view, "title"):
                        page_attr(title=get_view_attr(view, "title"))

                    response.setdefault("_template", _template)
                    response = i.render(**response)

            if not isinstance(response, Response):
                response = make_response(response)

            for ext in cls._ext:
                response = ext(response)

            after_view_name = "after_" + name
            if hasattr(i, after_view_name):
                after_view = getattr(i, after_view_name)
                response = after_view(response)

            if hasattr(i, "after_request"):
                response = i.after_request(name, response)

            return response

        return proxy
1169032
def render(request, templates, dictionary=None, context_instance=None,
           **kwargs):
    

    warnings.warn(
        "yacms.utils.views.render is deprecated and will be removed "
        "in a future version. Please update your project to use Django's "
        "TemplateResponse, which now provides equivalent functionality.",
        DeprecationWarning
    )

    dictionary = dictionary or {}
    if context_instance:
        context_instance.update(dictionary)
    else:
        context_instance = RequestContext(request, dictionary)
    return TemplateResponse(request, templates, context_instance, **kwargs)
1053866
def honeypot_exempt(view_func):
    
    # borrowing liberally from django's csrf_exempt
    def wrapped(*args, **kwargs):
        return view_func(*args, **kwargs)
    wrapped.honeypot_exempt = True
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped)
1153949
def as_view(cls, **initkwargs):
        
        # sanitize keyword arguments
        for key in initkwargs:
            if key in cls.http_method_names:
                raise TypeError("You tried to pass in the %s method name as a "
                                "keyword argument to %s(). Don't do that."
                                % (key, cls.__name__))
            if not hasattr(cls, key):
                raise TypeError("%s() received an invalid keyword %r. as_view "
                                "only accepts arguments that are already "
                                "attributes of the class." % (
                                    cls.__name__, key))

        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            if hasattr(self, 'get') and not hasattr(self, 'head'):
                self.head = self.get
            self.request = request
            self.args = args
            self.kwargs = kwargs
            self.authed_view = initkwargs.get('authed_view')
            self.authed_view_kwargs = initkwargs.get('authed_view_kwargs')
            self.anonymous_view = initkwargs.get('anonymous_view')
            self.anonymous_view_kwargs = initkwargs.get(
                'anonymous_view_kwargs')
            return self.dispatch(request, *args, **kwargs)
        # take name and docstring from class
        update_wrapper(view, cls, updated=())
        # and possible attributes set by decorators
        # like csrf_exempt from dispatch
        update_wrapper(view, cls.dispatch, assigned=())
        return view
1041839
def view_as_consumer(
        wrapped_view: typing.Callable[[HttpRequest], HttpResponse],
        mapped_actions: typing.Optional[
            typing.Dict[str, str]
        ]=None) -> Type[AsyncConsumer]:
    
    if mapped_actions is None:
        mapped_actions = {
            'create': 'PUT',
            'update': 'PATCH',
            'list': 'GET',
            'retrieve': 'GET'
        }

    class DjangoViewWrapper(DjangoViewAsConsumer):
        view = wrapped_view
        actions = mapped_actions

    return DjangoViewWrapper
175663
def show_as(**mappings):
    
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            g.show_request_fields = mappings
            g.show_response_fields = mappings
            return func(*args, **kwargs)
        return wrapper
    return decorator
189304
def request(request_callback=None, **kwargs):
    

    if request_callback is None:
        return lambda fn: request(fn, **kwargs)
    else:
        return Request(request_callback, **kwargs).decorate_module(request_callback)
384972
def basic_auth_required(view_func):
    
    @wraps(view_func)
    def wrapper(*args, **kwargs):
        if app.config.get('BASIC_AUTH_ACTIVE', False):
            if basic_auth.authenticate():
                return view_func(*args, **kwargs)
            else:
                return basic_auth.challenge()
        else:
            return view_func(*args, **kwargs)
    return wrapper
389601
def as_view(cls, action_map=None, **initkwargs):
        

        # Needs to re-implement the method but contains all the things the parent does.
        if not action_map:  # actions must not be empty
            raise TypeError("action_map is a required argument.")

        def view(request):
            self = cls(**initkwargs)
            self.request = request
            self.lookup_url_kwargs = self.request.matchdict
            self.action_map = action_map
            self.action = self.action_map.get(self.request.method.lower())

            for method, action in action_map.items():
                handler = getattr(self, action)
                setattr(self, method, handler)

            return self.dispatch(self.request, **self.request.matchdict)

        return view
211919
def wrap_view_func(self, app, rule, req, view_func, view_kwargs):
        
        operation = view_func.__module__ + "." + view_func.__name__
        return self.trace_view_function(
            view_func, ("Controller", {"path": req.path, "name": operation})
        )