Python functools.update_wrapper() Examples

The following are code examples for showing how to use functools.update_wrapper(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 8 votes vote down vote up
def test_selective_update(self):
        def f():
            pass
        f.attr = 'This is a different test'
        f.dict_attr = dict(a=1, b=2, c=3)
        def wrapper():
            pass
        wrapper.dict_attr = {}
        assign = ('attr',)
        update = ('dict_attr',)
        functools.update_wrapper(wrapper, f, assign, update)
        self.check_wrapper(wrapper, f, assign, update)
        self.assertEqual(wrapper.__name__, 'wrapper')
        self.assertEqual(wrapper.__doc__, None)
        self.assertEqual(wrapper.attr, 'This is a different test')
        self.assertEqual(wrapper.dict_attr, f.dict_attr) 
Example 2
Project: remote-pip   Author: danielfrg   File: main.py    Apache License 2.0 7 votes vote down vote up
def default_options(func):
    @click.option('--hosts', '-h', 'hosts', required=True, help='Comma separated hosts')
    @click.option('--user', '-u', 'user', required=False, help='Username to ssh')
    @click.option('--pkey', '-k', 'pkey', required=False, help='Path to the private key', type=click.Path(exists=True, resolve_path=True))
    @click.option('--pip-path', '-p', 'pip_path', required=False, help='Path to the pip binary in the remote nodes', default='/usr/bin/pip')
    @click.pass_context
    def new_func(ctx, hosts, user, pkey, pip_path, *args, **kwargs):
        hosts = hosts.split(',')

        if pkey:
            pkey = paramiko.RSAKey.from_private_key_file(pkey)

        ctx.obj['client'] = RemotePip(hosts=hosts, user=user, pkey=pkey, pip_path=pip_path)
        return ctx.invoke(func, *args, **kwargs)

    return update_wrapper(new_func, func) 
Example 3
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: wrappers.py    Apache License 2.0 6 votes vote down vote up
def application(cls, f):
        """Decorate a function as responder that accepts the request as first
        argument.  This works like the :func:`responder` decorator but the
        function is passed the request object as first argument and the
        request object will be closed automatically::

            @Request.application
            def my_wsgi_app(request):
                return Response('Hello World!')

        :param f: the WSGI callable to decorate
        :return: a new WSGI callable
        """
        #: return a callable that wraps the -2nd argument with the request
        #: and calls the function with all the arguments up to that one and
        #: the request.  The return value is then called with the latest
        #: two arguments.  This makes it possible to use this decorator for
        #: both methods and standalone WSGI functions.
        def application(*args):
            request = cls(args[-2])
            with request:
                return f(*args[:-2] + (request,))(*args[-2:])
        return update_wrapper(application, f) 
Example 4
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: wrappers.py    Apache License 2.0 6 votes vote down vote up
def application(cls, f):
        """Decorate a function as responder that accepts the request as first
        argument.  This works like the :func:`responder` decorator but the
        function is passed the request object as first argument and the
        request object will be closed automatically::

            @Request.application
            def my_wsgi_app(request):
                return Response('Hello World!')

        :param f: the WSGI callable to decorate
        :return: a new WSGI callable
        """
        #: return a callable that wraps the -2nd argument with the request
        #: and calls the function with all the arguments up to that one and
        #: the request.  The return value is then called with the latest
        #: two arguments.  This makes it possible to use this decorator for
        #: both methods and standalone WSGI functions.
        def application(*args):
            request = cls(args[-2])
            with request:
                return f(*args[:-2] + (request,))(*args[-2:])
        return update_wrapper(application, f) 
Example 5
Project: flasky   Author: RoseOu   File: langhelpers.py    MIT License 6 votes vote down vote up
def decorator(target):
    """A signature-matching decorator factory."""

    def decorate(fn):
        if not inspect.isfunction(fn):
            raise Exception("not a decoratable function")
        spec = compat.inspect_getfullargspec(fn)
        names = tuple(spec[0]) + spec[1:3] + (fn.__name__,)
        targ_name, fn_name = _unique_symbols(names, 'target', 'fn')

        metadata = dict(target=targ_name, fn=fn_name)
        metadata.update(format_argspec_plus(spec, grouped=False))
        metadata['name'] = fn.__name__
        code = """\
def %(name)s(%(args)s):
    return %(target)s(%(fn)s, %(apply_kw)s)
""" % metadata
        decorated = _exec_code_in_env(code,
                                      {targ_name: target, fn_name: fn},
                                      fn.__name__)
        decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__
        decorated.__wrapped__ = fn
        return update_wrapper(decorated, fn)
    return update_wrapper(decorate, target) 
Example 6
Project: flasky   Author: RoseOu   File: wrappers.py    MIT License 6 votes vote down vote up
def application(cls, f):
        """Decorate a function as responder that accepts the request as first
        argument.  This works like the :func:`responder` decorator but the
        function is passed the request object as first argument and the
        request object will be closed automatically::

            @Request.application
            def my_wsgi_app(request):
                return Response('Hello World!')

        :param f: the WSGI callable to decorate
        :return: a new WSGI callable
        """
        #: return a callable that wraps the -2nd argument with the request
        #: and calls the function with all the arguments up to that one and
        #: the request.  The return value is then called with the latest
        #: two arguments.  This makes it possible to use this decorator for
        #: both methods and standalone WSGI functions.
        def application(*args):
            request = cls(args[-2])
            with request:
                return f(*args[:-2] + (request,))(*args[-2:])
        return update_wrapper(application, f) 
Example 7
Project: django-glitter   Author: developersociety   File: blocks.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url, include

        if settings.DEBUG:
            self.check_dependencies()

        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        # Admin-site-wide views.
        urlpatterns = [
            url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
        ]

        # Add in each model's views.
        for model, model_admin in self._registry.items():
            urlpatterns += [
                url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name),
                    include(model_admin.urls))
            ]
        return urlpatterns

    # We have no logout here, so just raise PermissionDenied if needed 
Example 8
Project: django-glitter   Author: developersociety   File: blocks.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = [
            url(r'^add/(?P<version_id>\d+)/$', wrap(self.add_view), name='%s_%s_add' % info),
            url(r'^(.+)/continue/$', wrap(self.continue_view), name='%s_%s_continue' % info),
            url(r'^(.+)/$', wrap(self.change_view), name='%s_%s_change' % info),
        ]
        return urlpatterns 
Example 9
Project: uplink   Author: prkumar   File: commands.py    MIT License 6 votes vote down vote up
def __call__(
        self, func, request_definition_builder_factory=RequestDefinitionBuilder
    ):
        spec = utils.get_arg_spec(func)
        arg_handler = arguments.ArgumentAnnotationHandlerBuilder(
            func, spec.args
        )
        builder = request_definition_builder_factory(
            self._method,
            URIDefinitionBuilder(self._uri),
            arg_handler,
            decorators.MethodAnnotationHandlerBuilder(),
        )

        # Need to add the annotations after constructing the request
        # definition builder so it has a chance to attach its listener.
        arg_handler.set_annotations(spec.annotations)

        # Use return value type hint as expected return type
        if spec.return_annotation is not None:
            builder = returns.schema(spec.return_annotation)(builder)
        functools.update_wrapper(builder, func)
        builder = self._add_args(builder)
        return builder 
Example 10
Project: django-subadmin   Author: inueni   File: __init__.py    MIT License 6 votes vote down vote up
def get_urls(self):
        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        base_viewname = self.get_base_viewname()

        urlpatterns = [
            url(r'' , include(self.get_subadmin_urls())),
            url(r'^$', wrap(self.changelist_view), name='%s_changelist' % base_viewname),
            url(r'^add/$', wrap(self.add_view), name='%s_add' % base_viewname),
            url(r'^(.+)/history/$', wrap(self.history_view), name='%s_history' % base_viewname),
            url(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_delete' % base_viewname),
            url(r'^(.+)/change/$', wrap(self.change_view), name='%s_change' % base_viewname),
        ]

        urlpatterns =  urlpatterns
        return urlpatterns 
Example 11
Project: chattR   Author: patrickstocklin   File: options.py    GNU General Public License v2.0 6 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = [
            url(r'^$', wrap(self.changelist_view), name='%s_%s_changelist' % info),
            url(r'^add/$', wrap(self.add_view), name='%s_%s_add' % info),
            url(r'^(.+)/history/$', wrap(self.history_view), name='%s_%s_history' % info),
            url(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_%s_delete' % info),
            url(r'^(.+)/$', wrap(self.change_view), name='%s_%s_change' % info),
        ]
        return urlpatterns 
Example 12
Project: alfred-yubikey-otp   Author: robertoriv   File: util.py    MIT License 5 votes vote down vote up
def __init__(self, func, class_name=''):
        """Decorate `func`."""
        self.func = func
        functools.update_wrapper(self, func)
        self._caught_signal = None 
Example 13
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _default_update(self):
        def f():
            """This is a test"""
            pass
        f.attr = 'This is also a test'
        def wrapper():
            pass
        functools.update_wrapper(wrapper, f)
        return wrapper, f 
Example 14
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_no_update(self):
        def f():
            """This is a test"""
            pass
        f.attr = 'This is also a test'
        def wrapper():
            pass
        functools.update_wrapper(wrapper, f, (), ())
        self.check_wrapper(wrapper, f, (), ())
        self.assertEqual(wrapper.__name__, 'wrapper')
        self.assertEqual(wrapper.__doc__, None)
        self.assertFalse(hasattr(wrapper, 'attr')) 
Example 15
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_builtin_update(self):
        # Test for bug #1576241
        def wrapper():
            pass
        functools.update_wrapper(wrapper, max)
        self.assertEqual(wrapper.__name__, 'max')
        self.assertTrue(wrapper.__doc__.startswith('max(')) 
Example 16
Project: xadmin_bugfix   Author: vip68   File: sites.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 17
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: util.py    MIT License 5 votes vote down vote up
def __init__(self, func, class_name=''):
        """Decorate `func`."""
        self.func = func
        functools.update_wrapper(self, func)
        self._caught_signal = None 
Example 18
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: app.py    Apache License 2.0 5 votes vote down vote up
def setupmethod(f):
    """Wraps a method so that it performs a check in debug mode if the
    first request was already handled.
    """
    def wrapper_func(self, *args, **kwargs):
        if self.debug and self._got_first_request:
            raise AssertionError('A setup function was called after the '
                'first request was handled.  This usually indicates a bug '
                'in the application where a module was not imported '
                'and decorators or other functionality was called too late.\n'
                'To fix this make sure to import all your view modules, '
                'database models and everything related at a central place '
                'before the application starts serving requests.')
        return f(self, *args, **kwargs)
    return update_wrapper(wrapper_func, f) 
Example 19
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: blueprints.py    Apache License 2.0 5 votes vote down vote up
def record_once(self, func):
        """Works like :meth:`record` but wraps the function in another
        function that will ensure the function is only called once.  If the
        blueprint is registered a second time on the application, the
        function passed is not called.
        """
        def wrapper(state):
            if state.first_registration:
                func(state)
        return self.record(update_wrapper(wrapper, func)) 
Example 20
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def emits_module_deprecation_warning(f):
    def new_f(self, *args, **kwargs):
        with catch_warnings() as log:
            f(self, *args, **kwargs)
            self.assert_true(log, 'expected deprecation warning')
            for entry in log:
                self.assert_in('Modules are deprecated', str(entry['message']))
    return update_wrapper(new_f, f) 
Example 21
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: ctx.py    Apache License 2.0 5 votes vote down vote up
def copy_current_request_context(f):
    """A helper function that decorates a function to retain the current
    request context.  This is useful when working with greenlets.  The moment
    the function is decorated a copy of the request context is created and
    then pushed when the function is called.

    Example::

        import gevent
        from flask import copy_current_request_context

        @app.route('/')
        def index():
            @copy_current_request_context
            def do_some_work():
                # do some work here, it can access flask.request like you
                # would otherwise in the view function.
                ...
            gevent.spawn(do_some_work)
            return 'Regular response'

    .. versionadded:: 0.10
    """
    top = _request_ctx_stack.top
    if top is None:
        raise RuntimeError('This decorator can only be used at local scopes '
            'when a request context is on the stack.  For instance within '
            'view functions.')
    reqctx = top.copy()
    def wrapper(*args, **kwargs):
        with reqctx:
            return f(*args, **kwargs)
    return update_wrapper(wrapper, f) 
Example 22
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: app.py    Apache License 2.0 5 votes vote down vote up
def setupmethod(f):
    """Wraps a method so that it performs a check in debug mode if the
    first request was already handled.
    """
    def wrapper_func(self, *args, **kwargs):
        if self.debug and self._got_first_request:
            raise AssertionError('A setup function was called after the '
                'first request was handled.  This usually indicates a bug '
                'in the application where a module was not imported '
                'and decorators or other functionality was called too late.\n'
                'To fix this make sure to import all your view modules, '
                'database models and everything related at a central place '
                'before the application starts serving requests.')
        return f(self, *args, **kwargs)
    return update_wrapper(wrapper_func, f) 
Example 23
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def emits_module_deprecation_warning(f):
    def new_f(self, *args, **kwargs):
        with catch_warnings() as log:
            f(self, *args, **kwargs)
            self.assert_true(log, 'expected deprecation warning')
            for entry in log:
                self.assert_in('Modules are deprecated', str(entry['message']))
    return update_wrapper(new_f, f) 
Example 24
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: ctx.py    Apache License 2.0 5 votes vote down vote up
def copy_current_request_context(f):
    """A helper function that decorates a function to retain the current
    request context.  This is useful when working with greenlets.  The moment
    the function is decorated a copy of the request context is created and
    then pushed when the function is called.

    Example::

        import gevent
        from flask import copy_current_request_context

        @app.route('/')
        def index():
            @copy_current_request_context
            def do_some_work():
                # do some work here, it can access flask.request like you
                # would otherwise in the view function.
                ...
            gevent.spawn(do_some_work)
            return 'Regular response'

    .. versionadded:: 0.10
    """
    top = _request_ctx_stack.top
    if top is None:
        raise RuntimeError('This decorator can only be used at local scopes '
            'when a request context is on the stack.  For instance within '
            'view functions.')
    reqctx = top.copy()
    def wrapper(*args, **kwargs):
        with reqctx:
            return f(*args, **kwargs)
    return update_wrapper(wrapper, f) 
Example 25
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: formparser.py    Apache License 2.0 5 votes vote down vote up
def exhaust_stream(f):
    """Helper decorator for methods that exhausts the stream on return."""
    def wrapper(self, stream, *args, **kwargs):
        try:
            return f(self, stream, *args, **kwargs)
        finally:
            exhaust = getattr(stream, 'exhaust', None)
            if exhaust is not None:
                exhaust()
            else:
                while 1:
                    chunk = stream.read(1024 * 64)
                    if not chunk:
                        break
    return update_wrapper(wrapper, f) 
Example 26
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: wsgi.py    Apache License 2.0 5 votes vote down vote up
def responder(f):
    """Marks a function as responder.  Decorate a function with it and it
    will automatically call the return value as WSGI application.

    Example::

        @responder
        def application(environ, start_response):
            return Response('Hello World!')
    """
    return update_wrapper(lambda *a: f(*a)(*a[-2:]), f) 
Example 27
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: _compat.py    Apache License 2.0 5 votes vote down vote up
def native_string_result(func):
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs).encode('utf-8')
        return functools.update_wrapper(wrapper, func) 
Example 28
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: formparser.py    Apache License 2.0 5 votes vote down vote up
def exhaust_stream(f):
    """Helper decorator for methods that exhausts the stream on return."""
    def wrapper(self, stream, *args, **kwargs):
        try:
            return f(self, stream, *args, **kwargs)
        finally:
            exhaust = getattr(stream, 'exhaust', None)
            if exhaust is not None:
                exhaust()
            else:
                while 1:
                    chunk = stream.read(1024 * 64)
                    if not chunk:
                        break
    return update_wrapper(wrapper, f) 
Example 29
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: wsgi.py    Apache License 2.0 5 votes vote down vote up
def responder(f):
    """Marks a function as responder.  Decorate a function with it and it
    will automatically call the return value as WSGI application.

    Example::

        @responder
        def application(environ, start_response):
            return Response('Hello World!')
    """
    return update_wrapper(lambda *a: f(*a)(*a[-2:]), f) 
Example 30
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: local.py    Apache License 2.0 5 votes vote down vote up
def middleware(self, func):
        """Like `make_middleware` but for decorating functions.

        Example usage::

            @manager.middleware
            def application(environ, start_response):
                ...

        The difference to `make_middleware` is that the function passed
        will have all the arguments copied from the inner application
        (name, docstring, module).
        """
        return update_wrapper(self.make_middleware(func), func) 
Example 31
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 32
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 33
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 34
Project: django-click   Author: GaretJax   File: adapter.py    MIT License 5 votes vote down vote up
def pass_verbosity(f):
    """
    Marks a callback as wanting to receive the verbosity as a keyword argument.
    """
    def new_func(*args, **kwargs):
        kwargs['verbosity'] = click.get_current_context().verbosity
        return f(*args, **kwargs)
    return update_wrapper(new_func, f) 
Example 35
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: asyncsupport.py    MIT License 5 votes vote down vote up
def wrap_generate_func(original_generate):
    def _convert_generator(self, loop, args, kwargs):
        async_gen = self.generate_async(*args, **kwargs)
        try:
            while 1:
                yield loop.run_until_complete(async_gen.__anext__())
        except StopAsyncIteration:
            pass
    def generate(self, *args, **kwargs):
        if not self.environment.is_async:
            return original_generate(self, *args, **kwargs)
        return _convert_generator(self, asyncio.get_event_loop(), args, kwargs)
    return update_wrapper(generate, original_generate) 
Example 36
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: asyncsupport.py    MIT License 5 votes vote down vote up
def wrap_render_func(original_render):
    def render(self, *args, **kwargs):
        if not self.environment.is_async:
            return original_render(self, *args, **kwargs)
        loop = asyncio.get_event_loop()
        return loop.run_until_complete(self.render_async(*args, **kwargs))
    return update_wrapper(render, original_render) 
Example 37
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: asyncsupport.py    MIT License 5 votes vote down vote up
def wrap_block_reference_call(original_call):
    @internalcode
    async def async_call(self):
        rv = await concat_async(self._stack[self._depth](self._context))
        if self._context.eval_ctx.autoescape:
            rv = Markup(rv)
        return rv

    @internalcode
    def __call__(self):
        if not self._context.environment.is_async:
            return original_call(self)
        return async_call(self)

    return update_wrapper(__call__, original_call) 
Example 38
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: asyncsupport.py    MIT License 5 votes vote down vote up
def wrap_macro_invoke(original_invoke):
    @internalcode
    async def async_invoke(self, arguments, autoescape):
        rv = await self._func(*arguments)
        if autoescape:
            rv = Markup(rv)
        return rv

    @internalcode
    def _invoke(self, arguments, autoescape):
        if not self._environment.is_async:
            return original_invoke(self, arguments, autoescape)
        return async_invoke(self, arguments, autoescape)
    return update_wrapper(_invoke, original_invoke) 
Example 39
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: asyncsupport.py    MIT License 5 votes vote down vote up
def patch_template():
    from jinja2 import Template
    Template.generate = wrap_generate_func(Template.generate)
    Template.generate_async = update_wrapper(
        generate_async, Template.generate_async)
    Template.render_async = update_wrapper(
        render_async, Template.render_async)
    Template.render = wrap_render_func(Template.render)
    Template._get_default_module = wrap_default_module(
        Template._get_default_module)
    Template._get_default_module_async = get_default_module_async
    Template.make_module_async = update_wrapper(
        make_module_async, Template.make_module_async) 
Example 40
Project: flasky   Author: RoseOu   File: langhelpers.py    MIT License 5 votes vote down vote up
def __call__(self, fn):
        import_deps = self.import_deps
        spec = compat.inspect_getfullargspec(fn)

        spec_zero = list(spec[0])
        hasself = spec_zero[0] in ('self', 'cls')

        for i in range(len(import_deps)):
            spec[0][i + (1 if hasself else 0)] = "import_deps[%r]" % i

        inner_spec = format_argspec_plus(spec, grouped=False)

        for impname in import_deps:
            del spec_zero[1 if hasself else 0]
        spec[0][:] = spec_zero

        outer_spec = format_argspec_plus(spec, grouped=False)

        code = 'lambda %(args)s: fn(%(apply_kw)s)' % {
            "args": outer_spec['args'],
            "apply_kw": inner_spec['apply_kw']
        }

        decorated = eval(code, locals())
        decorated.__defaults__ = getattr(fn, 'im_func', fn).__defaults__
        return update_wrapper(decorated, fn) 
Example 41
Project: flasky   Author: RoseOu   File: app.py    MIT License 5 votes vote down vote up
def setupmethod(f):
    """Wraps a method so that it performs a check in debug mode if the
    first request was already handled.
    """
    def wrapper_func(self, *args, **kwargs):
        if self.debug and self._got_first_request:
            raise AssertionError('A setup function was called after the '
                'first request was handled.  This usually indicates a bug '
                'in the application where a module was not imported '
                'and decorators or other functionality was called too late.\n'
                'To fix this make sure to import all your view modules, '
                'database models and everything related at a central place '
                'before the application starts serving requests.')
        return f(self, *args, **kwargs)
    return update_wrapper(wrapper_func, f) 
Example 42
Project: flasky   Author: RoseOu   File: blueprints.py    MIT License 5 votes vote down vote up
def record_once(self, func):
        """Works like :meth:`record` but wraps the function in another
        function that will ensure the function is only called once.  If the
        blueprint is registered a second time on the application, the
        function passed is not called.
        """
        def wrapper(state):
            if state.first_registration:
                func(state)
        return self.record(update_wrapper(wrapper, func)) 
Example 43
Project: flasky   Author: RoseOu   File: __init__.py    MIT License 5 votes vote down vote up
def emits_module_deprecation_warning(f):
    def new_f(self, *args, **kwargs):
        with catch_warnings() as log:
            f(self, *args, **kwargs)
            self.assert_true(log, 'expected deprecation warning')
            for entry in log:
                self.assert_in('Modules are deprecated', str(entry['message']))
    return update_wrapper(new_f, f) 
Example 44
Project: flasky   Author: RoseOu   File: formparser.py    MIT License 5 votes vote down vote up
def exhaust_stream(f):
    """Helper decorator for methods that exhausts the stream on return."""
    def wrapper(self, stream, *args, **kwargs):
        try:
            return f(self, stream, *args, **kwargs)
        finally:
            exhaust = getattr(stream, 'exhaust', None)
            if exhaust is not None:
                exhaust()
            else:
                while 1:
                    chunk = stream.read(1024 * 64)
                    if not chunk:
                        break
    return update_wrapper(wrapper, f) 
Example 45
Project: flasky   Author: RoseOu   File: wsgi.py    MIT License 5 votes vote down vote up
def responder(f):
    """Marks a function as responder.  Decorate a function with it and it
    will automatically call the return value as WSGI application.

    Example::

        @responder
        def application(environ, start_response):
            return Response('Hello World!')
    """
    return update_wrapper(lambda *a: f(*a)(*a[-2:]), f) 
Example 46
Project: flasky   Author: RoseOu   File: local.py    MIT License 5 votes vote down vote up
def middleware(self, func):
        """Like `make_middleware` but for decorating functions.

        Example usage::

            @manager.middleware
            def application(environ, start_response):
                ...

        The difference to `make_middleware` is that the function passed
        will have all the arguments copied from the inner application
        (name, docstring, module).
        """
        return update_wrapper(self.make_middleware(func), func) 
Example 47
Project: flasky   Author: RoseOu   File: _compat.py    MIT License 5 votes vote down vote up
def native_string_result(func):
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs).encode('utf-8')
        return functools.update_wrapper(wrapper, func) 
Example 48
Project: alfred-urban-dictionary   Author: xilopaint   File: util.py    MIT License 5 votes vote down vote up
def __init__(self, func, class_name=''):
        """Decorate `func`."""
        self.func = func
        functools.update_wrapper(self, func)
        self._caught_signal = None 
Example 49
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: model.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, async_method, *args, **kwargs):
        super(NetworkInfoAsyncWrapper, self).__init__()

        self._gt = utils.spawn(async_method, *args, **kwargs)
        methods = ['json', 'fixed_ips', 'floating_ips']
        for method in methods:
            fn = getattr(self, method)
            wrapper = functools.partial(self._sync_wrapper, fn)
            functools.update_wrapper(wrapper, fn)
            setattr(self, method, wrapper) 
Example 50
Project: bigquerylayers   Author: smandaric   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def _update_wrapper(wrapper, wrapped):
        functools.update_wrapper(wrapper, wrapped)
        wrapper.__wrapped__ = wrapped
        return wrapper 
Example 51
Project: reportengine   Author: NNPDF   File: resourcebuilder.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, f):
        functools.update_wrapper(self, f)
        self.f = f 
Example 52
Project: hotdog-not-hotdog-app   Author: tobegit3hub   File: mobilenet_v1.py    Apache License 2.0 5 votes vote down vote up
def wrapped_partial(func, *args, **kwargs):
  partial_func = functools.partial(func, *args, **kwargs)
  functools.update_wrapper(partial_func, func)
  return partial_func 
Example 53
Project: relay-bench   Author: uwsampl   File: mobilenet.py    Apache License 2.0 5 votes vote down vote up
def wrapped_partial(func, *args, **kwargs):
  partial_func = functools.partial(func, *args, **kwargs)
  functools.update_wrapper(partial_func, func)
  return partial_func 
Example 54
Project: quart   Author: pgjones   File: blueprints.py    MIT License 5 votes vote down vote up
def record_once(self, func: DeferedSetupFunction) -> None:
        """Used to register a deferred action that happens only once."""

        def wrapper(state: "BlueprintSetupState") -> None:
            if state.first_registration:
                func(state)

        self.record(update_wrapper(wrapper, func)) 
Example 55
Project: where   Author: kartverket   File: cache.py    MIT License 5 votes vote down vote up
def __init__(self, fget):
        self.fget = fget
        functools.update_wrapper(self, fget) 
Example 56
Project: Image-Duplicate-Detection-using-Deep-Networks   Author: jiahuei   File: mobilenet_v2.py    Apache License 2.0 5 votes vote down vote up
def wrapped_partial(func, *args, **kwargs):
  partial_func = functools.partial(func, *args, **kwargs)
  functools.update_wrapper(partial_func, func)
  return partial_func


# Wrappers for mobilenet v2 with depth-multipliers. Be noticed that
# 'finegrain_classification_mode' is set to True, which means the embedding
# layer will not be shrinked when given a depth-multiplier < 1.0. 
Example 57
Project: Image-Duplicate-Detection-using-Deep-Networks   Author: jiahuei   File: mobilenet_v1.py    Apache License 2.0 5 votes vote down vote up
def wrapped_partial(func, *args, **kwargs):
  partial_func = functools.partial(func, *args, **kwargs)
  functools.update_wrapper(partial_func, func)
  return partial_func 
Example 58
Project: django-glitter   Author: developersociety   File: admin.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_urls(self):
        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)
        urlpatterns = super().get_urls()

        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = [
            url(r'^$', wrap(self.grid_view)),
            url(r'^tree/$', wrap(self.changelist_view), name='%s_%s_tree' % info),
            url(r'^(\d+)/duplicate/$', wrap(self.duplicate_page), name='%s_%s_duplicate' % info),
        ] + urlpatterns
        return urlpatterns 
Example 59
Project: django-glitter   Author: developersociety   File: blocks.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        def inner(request, *args, **kwargs):
            if not self.has_permission(request):
                raise PermissionDenied
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        inner = csrf_protect(inner)
        return update_wrapper(inner, view) 
Example 60
Project: razzy-spinner   Author: rafasashi   File: compat.py    GNU General Public License v3.0 5 votes vote down vote up
def _transliterated(method):
    def wrapper(self):
        return transliterate(method(self))

    functools.update_wrapper(wrapper, method, ["__name__", "__doc__"])
    if hasattr(method, "_nltk_compat_7bit"):
        wrapper._nltk_compat_7bit = method._nltk_compat_7bit

    wrapper._nltk_compat_transliterated = True
    return wrapper 
Example 61
Project: razzy-spinner   Author: rafasashi   File: compat.py    GNU General Public License v3.0 5 votes vote down vote up
def _7bit(method):
    def wrapper(self):
        return method(self).encode('ascii', 'backslashreplace')

    functools.update_wrapper(wrapper, method, ["__name__", "__doc__"])

    if hasattr(method, "_nltk_compat_transliterated"):
        wrapper._nltk_compat_transliterated = method._nltk_compat_transliterated

    wrapper._nltk_compat_7bit = True
    return wrapper 
Example 62
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: pydevd_thread_wrappers.py    MIT License 5 votes vote down vote up
def __init__(self, obj):
        self.wrapped_object = obj
        try:
            import functools
            functools.update_wrapper(self, obj)
        except:
            pass 
Example 63
Project: gist-alfred   Author: danielecook   File: util.py    MIT License 5 votes vote down vote up
def __init__(self, func, class_name=''):
        """Decorate `func`."""
        self.func = func
        functools.update_wrapper(self, func)
        self._caught_signal = None 
Example 64
Project: uplink   Author: prkumar   File: decorators.py    MIT License 5 votes vote down vote up
def __new__(cls, func=None, *args, **kwargs):
        if func is None:
            return lambda f: cls(f, *args, **kwargs)
        self = super(_BaseHandlerAnnotation, cls).__new__(cls)
        functools.update_wrapper(self, func)
        return self


# noinspection PyPep8Naming 
Example 65
Project: uplink   Author: prkumar   File: models.py    MIT License 5 votes vote down vote up
def __call__(self, func):
        converter = _Wrapper(self.using(func), func)
        functools.update_wrapper(converter, func)
        return converter 
Example 66
Project: poty-scripts   Author: zhuyifei1999   File: properties.py    MIT License 5 votes vote down vote up
def __init__(self, func):
        self.__func__ = func
        functools.update_wrapper(self, func) 
Example 67
Project: poty-scripts   Author: zhuyifei1999   File: properties.py    MIT License 5 votes vote down vote up
def __init__(self, func):
        super(classproperty, self).__init__(classmethod(func))
        functools.update_wrapper(self, func) 
Example 68
Project: keyword2cmdline   Author: wecacuee   File: keyword2cmdline.py    MIT License 5 votes vote down vote up
def __init__(self, func,
                 parser_factory = recpartial(
                     ArgParserKWArgs,
                     {"parser_factory.kwonly": True})):
        self.func = func
        self._parser = parser = parser_factory(func)
        if not isinstance(self.parser, Parser):
            raise ValueError("parser_factory should return "
                             + " keyword2cmdline.Parser object")
        functools.update_wrapper(self, func) 
Example 69
Project: OpenBottle   Author: xiaozhuchacha   File: compat.py    MIT License 5 votes vote down vote up
def _transliterated(method):
    def wrapper(self):
        return transliterate(method(self))

    functools.update_wrapper(wrapper, method, ["__name__", "__doc__"])
    if hasattr(method, "_nltk_compat_7bit"):
        wrapper._nltk_compat_7bit = method._nltk_compat_7bit

    wrapper._nltk_compat_transliterated = True
    return wrapper 
Example 70
Project: OpenBottle   Author: xiaozhuchacha   File: compat.py    MIT License 5 votes vote down vote up
def _7bit(method):
    def wrapper(self):
        return method(self).encode('ascii', 'backslashreplace')

    functools.update_wrapper(wrapper, method, ["__name__", "__doc__"])

    if hasattr(method, "_nltk_compat_transliterated"):
        wrapper._nltk_compat_transliterated = method._nltk_compat_transliterated

    wrapper._nltk_compat_7bit = True
    return wrapper 
Example 71
Project: OpenBottle   Author: xiaozhuchacha   File: compat.py    MIT License 5 votes vote down vote up
def _transliterated(method):
    def wrapper(self):
        return transliterate(method(self))

    functools.update_wrapper(wrapper, method, ["__name__", "__doc__"])
    if hasattr(method, "_nltk_compat_7bit"):
        wrapper._nltk_compat_7bit = method._nltk_compat_7bit

    wrapper._nltk_compat_transliterated = True
    return wrapper 
Example 72
Project: xadmin_bugfix   Author: vip68   File: sites.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get_urls(self):
        from django.urls import include, path, re_path
        from xadmin.views.base import BaseAdminView

        if settings.DEBUG:
            self.check_dependencies()

        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)
            wrapper.admin_site = self
            return update_wrapper(wrapper, view)

        # Admin-site-wide views.
        urlpatterns = [
            path('jsi18n/', wrap(self.i18n_javascript, cacheable=True), name='jsi18n')
        ]

        # Registed admin views
        # inspect[isclass]: Only checks if the object is a class. With it lets you create an custom view that
        # inherits from multiple views and have more of a metaclass.
        urlpatterns += [
            re_path(
                _path,
                wrap(self.create_admin_view(clz_or_func))
                if inspect.isclass(clz_or_func) and issubclass(clz_or_func, BaseAdminView)
                else include(clz_or_func(self)),
                name=name
            )
            for _path, clz_or_func, name in self._registry_views
        ]

        # Add in each model's views.
        for model, admin_class in iteritems(self._registry):
            view_urls = [
                re_path(
                    _path,
                    wrap(self.create_model_admin_view(clz, model, admin_class)),
                    name=name % (model._meta.app_label, model._meta.model_name)
                )
                for _path, clz, name in self._registry_modelviews
            ]
            urlpatterns += [
                re_path(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(view_urls))
            ]
        return urlpatterns 
Example 73
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 4 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url, include
        from xadmin.views.base import BaseAdminView

        if settings.DEBUG:
            self.check_dependencies()

        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        # Admin-site-wide views.
        urlpatterns = [
            url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n')
        ]

        # Registed admin views
        # inspect[isclass]: Only checks if the object is a class. With it lets you create an custom view that
        # inherits from multiple views and have more of a metaclass.
        urlpatterns += [
            url(
                path,
                wrap(self.create_admin_view(clz_or_func))
                if inspect.isclass(clz_or_func) and issubclass(clz_or_func, BaseAdminView)
                else include(clz_or_func(self)),
                name=name
            )
            for path, clz_or_func, name in self._registry_views
        ]

        # Add in each model's views.
        for model, admin_class in iteritems(self._registry):
            view_urls = [
                url(
                    path,
                    wrap(self.create_model_admin_view(clz, model, admin_class)),
                    name=name % (model._meta.app_label, model._meta.model_name)
                )
                for path, clz, name in self._registry_modelviews
            ]
            urlpatterns += [
                url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(view_urls))
            ]
        return urlpatterns 
Example 74
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 4 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url, include
        from xadmin.views.base import BaseAdminView

        if settings.DEBUG:
            self.check_dependencies()

        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        # Admin-site-wide views.
        urlpatterns = [
            url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n')
        ]

        # Registed admin views
        # inspect[isclass]: Only checks if the object is a class. With it lets you create an custom view that
        # inherits from multiple views and have more of a metaclass.
        urlpatterns += [
            url(
                path,
                wrap(self.create_admin_view(clz_or_func))
                if inspect.isclass(clz_or_func) and issubclass(clz_or_func, BaseAdminView)
                else include(clz_or_func(self)),
                name=name
            )
            for path, clz_or_func, name in self._registry_views
        ]

        # Add in each model's views.
        for model, admin_class in iteritems(self._registry):
            view_urls = [
                url(
                    path,
                    wrap(self.create_model_admin_view(clz, model, admin_class)),
                    name=name % (model._meta.app_label, model._meta.model_name)
                )
                for path, clz, name in self._registry_modelviews
            ]
            urlpatterns += [
                url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(view_urls))
            ]
        return urlpatterns 
Example 75
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: wsgi.py    Apache License 2.0 4 votes vote down vote up
def __getattribute__(self, key):

        def version_select(*args, **kwargs):
            """Look for the method which matches the name supplied and version
            constraints and calls it with the supplied arguments.

            @return: Returns the result of the method called
            @raises: VersionNotFoundForAPIMethod if there is no method which
                 matches the name and version constraints
            """

            # The first arg to all versioned methods is always the request
            # object. The version for the request is attached to the
            # request object
            if len(args) == 0:
                ver = kwargs['req'].api_version_request
            else:
                ver = args[0].api_version_request

            func_list = self.versioned_methods[key]
            for func in func_list:
                if ver.matches(func.start_version, func.end_version):
                    # Update the version_select wrapper function so
                    # other decorator attributes like wsgi.response
                    # are still respected.
                    functools.update_wrapper(version_select, func.func)
                    return func.func(self, *args, **kwargs)

            # No version match
            raise exception.VersionNotFoundForAPIMethod(version=ver)

        try:
            version_meth_dict = object.__getattribute__(self, VER_METHOD_ATTR)
        except AttributeError:
            # No versioning on this class
            return object.__getattribute__(self, key)

        if version_meth_dict and \
          key in object.__getattribute__(self, VER_METHOD_ATTR):
            return version_select

        return object.__getattribute__(self, key)

    # NOTE(cyeoh): This decorator MUST appear first (the outermost
    # decorator) on an API method for it to work correctly 
Example 76
Project: bigquerylayers   Author: smandaric   File: func.py    GNU General Public License v3.0 4 votes vote down vote up
def _cache(cache, typed=False):
    def decorator(func):
        key = keys.typedkey if typed else keys.hashkey
        lock = RLock()
        stats = [0, 0]

        def cache_info():
            with lock:
                hits, misses = stats
                maxsize = cache.maxsize
                currsize = cache.currsize
            return _CacheInfo(hits, misses, maxsize, currsize)

        def cache_clear():
            with lock:
                try:
                    cache.clear()
                finally:
                    stats[:] = [0, 0]

        def wrapper(*args, **kwargs):
            k = key(*args, **kwargs)
            with lock:
                try:
                    v = cache[k]
                    stats[0] += 1
                    return v
                except KeyError:
                    stats[1] += 1
            v = func(*args, **kwargs)
            try:
                with lock:
                    cache[k] = v
            except ValueError:
                pass  # value too large
            return v
        functools.update_wrapper(wrapper, func)
        if not hasattr(wrapper, '__wrapped__'):
            wrapper.__wrapped__ = func  # Python 2.7
        wrapper.cache_info = cache_info
        wrapper.cache_clear = cache_clear
        return wrapper
    return decorator 
Example 77
Project: mimic   Author: googlearchive   File: lazy.py    Apache License 2.0 4 votes vote down vote up
def LazyProperty(func):
  """A decorator for lazily calculated properties.

  This decorator implicitly creates a read-only property with added logic
  to cache the result.  It can be used in conjuction with the LazyBase
  base class, or completely on its own.

  Typical use:

  class Foo(obect):

    @lazy.LazyProperty
    def bar(self):
      ...

  f = Foo()
  f.bar  # will return result of f.bar()
  f.bar  # will return previous result without calling bar() again

  Args:
    func: A function that computes the value of the property.

  Returns:
    A property object.
  """

  def _LazyFunc(self):
    name = func.__name__
    try:
      return self._LazyBase__lazy_values[name]  # pylint: disable-msg=W0212
    except AttributeError:
      # auto-populate this attribute so that no __init__ code is required
      self._LazyBase__lazy_values = {}
    except KeyError:
      # property hasn't been evaluated yet, fall through
      pass
    # call the underlying function to compute the value
    value = func(self)
    self._LazyBase__lazy_values[name] = value  # pylint: disable-msg=W0212
    return value

  functools.update_wrapper(_LazyFunc, func)
  return property(_LazyFunc) 
Example 78
Project: django-glitter   Author: developersociety   File: admin.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get_urls(self):

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = [
            # Start a page with a brand new template
            url(r'^(?P<object_id>\d+)/template/$',
                wrap(self.page_template_view),
                name='%s_%s_template' % info),

            # Redirect a user to view the latest appropriate page
            url(r'^(?P<object_id>\d+)/redirect/$',
                wrap(self.page_redirect_view),
                name='%s_%s_redirect' % info),

            # View and edit
            url(r'^editor/view/(?P<version_id>\d+)/$',
                wrap(self.page_version_view),
                name='%s_%s_version' % info),
            url(r'^editor/edit/(?P<version_id>\d+)/$',
                wrap(self.page_edit_view),
                name='%s_%s_edit' % info),

            # Change template
            url(r'^editor/changetemplate/(?P<version_id>\d+)/$',
                wrap(self.page_changetemplate_view),
                name='%s_%s_changetemplate' % info),

            # Save, publish, discard
            url(r'^edit/page/(?P<version_id>\d+)/save/$',
                wrap(self.page_save_view),
                name='%s_%s_save' % info),
            url(r'^edit/page/(?P<version_id>\d+)/publish/$',
                wrap(self.page_publish_view),
                name='%s_%s_publish' % info),
            url(r'^edit/page/(?P<version_id>\d+)/unpublish/$',
                wrap(self.page_unpublish_view),
                name='%s_%s_unpublish' % info),
            url(r'^edit/page/(?P<version_id>\d+)/discard/$',
                wrap(self.page_discard_view),
                name='%s_%s_discard' % info),

            # Block editing/updating/moving
            url(r'^edit/block/del/(?P<contentblock_id>\d+)/$',
                wrap(self.page_block_delete_view),
                name='%s_%s_block_delete' % info),
            url(r'^edit/block/move/(?P<contentblock_id>\d+)/$',
                wrap(self.page_block_move_view),
                name='%s_%s_block_move' % info),
            url(r'^edit/block/column/(?P<contentblock_id>\d+)/$',
                wrap(self.page_block_column_view),
                name='%s_%s_block_column' % info),

        ] + super().get_urls()
        return urlpatterns 
Example 79
Project: chattR   Author: patrickstocklin   File: sites.py    GNU General Public License v2.0 4 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request):
                if request.path == reverse('admin:logout', current_app=self.name):
                    index_path = reverse('admin:index', current_app=self.name)
                    return HttpResponseRedirect(index_path)
                # Inner import to prevent django.contrib.admin (app) from
                # importing django.contrib.auth.models.User (unrelated model).
                from django.contrib.auth.views import redirect_to_login
                return redirect_to_login(
                    request.get_full_path(),
                    reverse('admin:login', current_app=self.name)
                )
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        if not getattr(view, 'csrf_exempt', False):
            inner = csrf_protect(inner)
        return update_wrapper(inner, view) 
Example 80
Project: chattR   Author: patrickstocklin   File: sites.py    GNU General Public License v2.0 4 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url, include
        # Since this module gets imported in the application's root package,
        # it cannot import models from other applications at the module level,
        # and django.contrib.contenttypes.views imports ContentType.
        from django.contrib.contenttypes import views as contenttype_views

        if settings.DEBUG:
            self.check_dependencies()

        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        # Admin-site-wide views.
        urlpatterns = [
            url(r'^$', wrap(self.index), name='index'),
            url(r'^login/$', self.login, name='login'),
            url(r'^logout/$', wrap(self.logout), name='logout'),
            url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'),
            url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True),
                name='password_change_done'),
            url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
            url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', wrap(contenttype_views.shortcut),
                name='view_on_site'),
        ]

        # Add in each model's views, and create a list of valid URLS for the
        # app_index
        valid_app_labels = []
        for model, model_admin in six.iteritems(self._registry):
            urlpatterns += [
                url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)),
            ]
            if model._meta.app_label not in valid_app_labels:
                valid_app_labels.append(model._meta.app_label)

        # If there were ModelAdmins registered, we should have a list of app
        # labels for which we need to allow access to the app_index view,
        if valid_app_labels:
            regex = r'^(?P<app_label>' + '|'.join(valid_app_labels) + ')/$'
            urlpatterns += [
                url(regex, wrap(self.app_index), name='app_list'),
            ]
        return urlpatterns