Decorator applied specifically to a view's get method
359705
def cached_get(timeout, *params):
    """"""

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(view_or_request, *args, **kwargs):

            # The type of the request gets muddled when using a function based
            # decorator. We must use a function based decorator so it can be
            # used in urls.py.
            request = getattr(view_or_request, "request", view_or_request)

            if not hasattr(_thread_locals, "ultracache_request"):
                setattr(_thread_locals, "ultracache_request", request)

            # If request not GET or HEAD never cache
            if request.method.lower() not in ("get", "head"):
                return view_func(view_or_request, *args, **kwargs)

            # If request contains messages never cache
            l = 0
            try:
                l = len(request._messages)
            except (AttributeError, TypeError):
                pass
            if l:
                return view_func(view_or_request, *args, **kwargs)

            # Compute a cache key
            li = [str(view_or_request.__class__), view_func.__name__]

            # request.get_full_path is implicitly added it no other request
            # path is provided. get_full_path includes the querystring and is
            # the more conservative approach but makes it trivially easy for a
            # request to bust through the cache.
            if not set(params).intersection(set((
                "request.get_full_path()", "request.path", "request.path_info"
            ))):
                li.append(request.get_full_path())

            if "django.contrib.sites" in settings.INSTALLED_APPS:
                li.append(get_current_site_pk(request))

            # Pre-sort kwargs
            keys = list(kwargs.keys())
            keys.sort()
            for key in keys:
                li.append("%s,%s" % (key, kwargs[key]))

            # Extend cache key with custom variables
            for param in params:
                if not isinstance(param, str):
                    param = str(param)
                li.append(eval(param))

            s = ":".join([str(l) for l in li])
            hashed = hashlib.md5(s.encode("utf-8")).hexdigest()
            cache_key = "ucache-get-%s" % hashed
            cached = cache.get(cache_key, None)
            if cached is None:
                # The get view as outermost caller may bluntly set _ultracache
                request._ultracache = []
                response = view_func(view_or_request, *args, **kwargs)
                content = None
                if isinstance(response, TemplateResponse):
                    content = response.render().rendered_content
                elif isinstance(response, HttpResponse):
                    content = response.content
                if content is not None:
                    headers = getattr(response, "_headers", {})
                    cache.set(
                        cache_key,
                        {"content": content, "headers": headers},
                        timeout
                    )
                    cache_meta(request, cache_key)
            else:
                response = HttpResponse(cached["content"])
                # Headers has a non-obvious format
                for k, v in cached["headers"].items():
                    response[v[0]] = v[1]

            return response

        return _wrapped_view
    return decorator
660113
def view_func(self):
        
        if request is None:
            raise RuntimeError('view_func need Flask be installed')

        signature = request.args.get('signature')
        timestamp = request.args.get('timestamp')
        nonce = request.args.get('nonce')
        if not self.validate(signature, timestamp, nonce):
            return 'signature failed', 400

        if request.method == 'GET':
            echostr = request.args.get('echostr', '')
            return echostr

        try:
            ret = self.parse(request.data)
        except ValueError:
            return 'invalid', 400

        if 'type' not in ret:
            # not a valid message
            return 'invalid', 400

        if ret['type'] == 'text' and ret['content'] in self._registry:
            func = self._registry[ret['content']]
        else:
            ret_set = frozenset(ret.items())
            matched_rules = (
                _func for _func, _limitation in self._registry_without_key
                if _limitation.issubset(ret_set))
            func = next(matched_rules, None)  # first matched rule

        if func is None:
            if '*' in self._registry:
                func = self._registry['*']
            else:
                func = 'failed'

        if callable(func):
            text = func(**ret)
        else:
            # plain text
            text = self.reply(
                username=ret['sender'],
                sender=ret['receiver'],
                content=func,
            )

        return Response(text, content_type='text/xml; charset=utf-8')
549743
def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
    
    def decorator(view_func):
        @functools.wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if is_authenticated(request.user):
                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
1333895
def get_request_from_view_args(
        self, view: typing.Callable, args: typing.Iterable, kwargs: typing.Mapping
    ) -> Request:
        
        req = None
        for arg in args:
            if isinstance(arg, web.Request):
                req = arg
                break
            elif isinstance(arg, web.View):
                req = arg.request
                break
        assert isinstance(req, web.Request), "Request argument not found for handler"
        return req
1269496
def get_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):
    '''
    
    '''
    # first check the cache (without doing locks)
    key = ( module_name, function_name )
    try:
        return CACHED_VIEW_FUNCTIONS[key]
    except KeyError:
        with rlock:
            # try again now that we're locked
            try:
                return CACHED_VIEW_FUNCTIONS[key]
            except KeyError:
                # if we get here, we need to load the view function
                func = find_view_function(module_name, function_name, fallback_app, fallback_template, verify_decorator)
                # cache in production mode
                if not settings.DEBUG:
                    CACHED_VIEW_FUNCTIONS[key] = func
                return func

    # the code should never be able to get here
    raise Exception("Django-Mako-Plus error: get_view_function() should not have been able to get to this point.  Please notify the owner of the DMP project.  Thanks.")
190469
def _get_view_result(view, raw_result, **kwargs):
        
        if raw_result:
            return view(**kwargs)
        if kwargs:
            return Result(view, **kwargs)

        return view.result
34055
def decorate(self, view):
		
		from functools import wraps

		@wraps(view)
		def decorated(*args, **kwargs):
			response = view(*args, **kwargs)
			accept = self.get_accept()
			return self.output(response, accept)
		return decorated
679876
def make_proxy_method(cls, name):
        

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

        if cls.decorators:
            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:
                    df_v_t = "%s/%s.html" % (cls.__name__, view.__name__)
                    response.setdefault("template_", df_v_t)
                    response = i.render_(**response)

            if not isinstance(response, Response):
                response = make_response(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
13181
def get(self, obj, cls):
    
    method = self._cache.get(cls)
    if not method:
      name = "visit_" + cls.__name__.lower()
      method = getattr(obj, name, obj.visit_default)
      self._cache[cls] = method
    return method
1078034
def get_base_wrappers(method='get', template_name='', predicates=(), wrappers=()):
    
    wrappers += (preserve_view(MethodPredicate(method), *predicates),)

    if template_name:
        wrappers += (render_template(template_name),)

    return wrappers
976609
def get_serializer_class(self, view, method_func):
        
        if hasattr(method_func, 'request_serializer'):
            return getattr(method_func, 'request_serializer')

        if hasattr(view, 'serializer_class'):
            return getattr(view, 'serializer_class')

        if hasattr(view, 'get_serializer_class'):
            return getattr(view, 'get_serializer_class')()

        return None
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
997593
def get(self, request, *args, **kwargs):
        
        self.set_test_cookie()
        return super(LoginView, self).get(request, *args, **kwargs)
151563
def view_getattr():
    

    def view_getattr(_value, context, **_params):
        value = getattr(context["view"], context["key"])
        return _attr(value)

    return view_getattr
544462
def model_get(method_name):
    

    def model_get(_value, context, **_params):
        method = getattr(context["model"], method_name)
        return _get(method, context["key"], (), {})

    return model_get
140603
def cbv_decorator(function_decorator):
    """"""

    def class_decorator(View):
        View.dispatch = method_decorator(function_decorator)(View.dispatch)
        return View
    return class_decorator
421297
def from_view(cls, view, *methods, name=None):
        """"""
        docs = getattr(view, '__doc__', None)
        view = to_coroutine(view)
        methods = methods or ['GET']

        if METH_ANY in methods:
            methods = METH_ALL

        def proxy(self, *args, **kwargs):
            return view(*args, **kwargs)

        params = {m.lower(): proxy for m in methods}
        params['methods'] = methods
        if docs:
            params['__doc__'] = docs

        return type(name or view.__name__, (cls,), params)