Page view decorator.

    Put that around a state handler function in order to log a page view each
    time the handler gets called.

    :param url: simili-URL that you want to give to the state
491418
def page_view(url):
    

    def decorator(func):
        @wraps(func)
        async def wrapper(self: BaseState, *args, **kwargs):
            user_id = self.request.user.id

            try:
                user_lang = await self.request.user.get_locale()
            except NotImplementedError:
                user_lang = ''

            title = self.__class__.__name__

            # noinspection PyTypeChecker
            async for p in providers():
                await p.page_view(url, title, user_id, user_lang)

            return await func(self, *args, **kwargs)
        return wrapper
    return decorator
694818
def _load(self, url, verbose):
        
        msg = u"_load url: %s" % url
        self._last_query_str = url
        log.debug(msg)
        if verbose:
            print msg
        response = self.__api__.request(url)
        return response
521100
def listen(url, prefix=None, **kwargs):
    
    return listener(url, prefix=get_prefix(prefix), **kwargs)
186991
def handle_page_crumb(func):
    
    @wraps(func)
    def wrapper(path, model, page, root_name):
        path = PAGE_REGEXP.sub('', path)
        breadcrumbs = func(path, model, root_name)
        if page:
            if page.number > 1:
                breadcrumbs[-1].url = path
                page_crumb = Crumb(_('Page %s') % page.number)
                breadcrumbs.append(page_crumb)
        return breadcrumbs
    return wrapper
171343
def is_url_for(cls, _action, _endpoint=None, _app=None, _external=None, **paramattrs):
        
        def decorator(f):
            if 'url_for_endpoints' not in cls.__dict__:
                cls.url_for_endpoints = {None: {}}  # Stick it into the class with the first endpoint
            cls.url_for_endpoints.setdefault(_app, {})

            for keyword in paramattrs:
                if isinstance(paramattrs[keyword], six.string_types) and '.' in paramattrs[keyword]:
                    paramattrs[keyword] = tuple(paramattrs[keyword].split('.'))
            cls.url_for_endpoints[_app][_action] = _endpoint or f.__name__, paramattrs, _external
            return f
        return decorator
1234618
def session_state_view(request, template_name, **kwargs):
    ''

    session = request.session

    demo_count = session.get('django_plotly_dash', {})

    ind_use = demo_count.get('ind_use', 0)
    ind_use += 1
    demo_count['ind_use'] = ind_use

    context = {'ind_use' : ind_use}

    session['django_plotly_dash'] = demo_count

    return render(request, template_name=template_name, context=context)
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
405650
def register_views(self, app):
        

        # Wrap the views in an arbitrary number of decorators.
        def wrap_view(view):
            if self.decorators:
                for decorator in self.decorators:
                    view = decorator(view)
            return view

        if self.config.get('swagger_ui', True):
            uiversion = self.config.get('uiversion', 3)
            blueprint = Blueprint(
                self.config.get('endpoint', 'flasgger'),
                __name__,
                url_prefix=self.config.get('url_prefix', None),
                subdomain=self.config.get('subdomain', None),
                template_folder=self.config.get(
                    'template_folder', 'ui{0}/templates'.format(uiversion)
                ),
                static_folder=self.config.get(
                    'static_folder', 'ui{0}/static'.format(uiversion)
                ),
                static_url_path=self.config.get('static_url_path', None)
            )

            blueprint.add_url_rule(
                self.config.get('specs_route', '/apidocs/'),
                'apidocs',
                view_func=wrap_view(APIDocsView().as_view(
                    'apidocs',
                    view_args=dict(config=self.config)
                ))
            )

            # backwards compatibility with old url style
            blueprint.add_url_rule(
                '/apidocs/index.html',
                view_func=lambda: redirect(url_for('flasgger.apidocs'))
            )
        else:
            blueprint = Blueprint(
                self.config.get('endpoint', 'flasgger'),
                __name__
            )

        for spec in self.config['specs']:
            self.endpoints.append(spec['endpoint'])
            blueprint.add_url_rule(
                spec['route'],
                spec['endpoint'],
                view_func=wrap_view(APISpecsView.as_view(
                    spec['endpoint'],
                    loader=partial(
                        self.get_apispecs, endpoint=spec['endpoint'])
                ))
            )

        app.register_blueprint(blueprint)
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
1155557
def as_view(cls, *class_args, **class_kwargs):
        

        def view(*args, **kwargs):
            self = view.view_class(*class_args, **class_kwargs)
            return self.dispatch_request(*args, **kwargs)

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

        view.view_class = cls
        view.__doc__ = cls.__doc__
        view.__module__ = cls.__module__
        view.__name__ = cls.__name__
        return view
1193002
def view(template=None):
    
    if not template:
        template = "Juice/Plugin/MaintenancePage/index.html"

    class Maintenance(View):

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

            if cls.get_config("APPLICATION_MAINTENANCE_ON"):
                app.logger.info("APPLICATION MAINTENANCE PAGE IS ON")

                @app.before_request
                def on_maintenance():
                    return cls.render_(layout_=template), 503

    return Maintenance
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
1227838
def jsonp(func):
    

    @functools.wraps(func)
    def decorated_view(*args, **kwargs):
        callback = request.args.get('callback', None)
        if callback:
            data = str(func(*args, **kwargs))
            content = str(callback) + '(' + data + ')'
            mimetype = 'application/javascript'
            return current_app.response_class(content, mimetype=mimetype)
        else:
            return func(*args, **kwargs)
    return decorated_view
233804
def http_methods(self, urls=None, **route_data):
        """"""
        def decorator(class_definition):
            instance = class_definition
            if isinstance(class_definition, type):
                instance = class_definition()

            router = self.urls(urls if urls else "/{0}".format(instance.__class__.__name__.lower()), **route_data)
            for method in HTTP_METHODS:
                handler = getattr(instance, method.lower(), None)
                if handler:
                    http_routes = getattr(handler, '_hug_http_routes', ())
                    if http_routes:
                        for route in http_routes:
                            http(**router.accept(method).where(**route).route)(handler)
                    else:
                        http(**router.accept(method).route)(handler)

                    cli_routes = getattr(handler, '_hug_cli_routes', ())
                    if cli_routes:
                        for route in cli_routes:
                            cli(**self.where(**route).route)(handler)
            return class_definition
        return decorator
1264583
def visit_page(self, page):
    

    url = urljoin(django_url(self), page)
    self.given('I visit "%s"' % url)
383585
def wrap_handler(cls, handler, protocol, **kwargs):
        '''  '''
        def _wrapper(request, *args, **kwargs):
            instance = cls(request=request, **kwargs)
            if protocol == Resource.Protocol.http:
                return instance._wrap_http(handler, request=request, **kwargs)
            elif protocol == Resource.Protocol.websocket:
                return instance._wrap_ws(handler, request=request, **kwargs)
            elif protocol == Resource.Protocol.amqp:
                return instance._wrap_amqp(view_type, *args, **kwargs)
            else:
                raise Exception('Communication protocol not specified')
        return _wrapper
698760
def get_view_response(self, request, page, view_func, view_args, view_kwargs):
        
        return view_func(request, page, *view_args, **view_kwargs)