Python functools.wraps() Examples

The following are code examples for showing how to use functools.wraps(). 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: fs_image   Author: facebookincubator   File: temp_subvolumes.py    MIT License 6 votes vote down vote up
def with_temp_subvols(method):
    '''
    A test that needs a TempSubvolumes instance should use this decorator.
    This is a cleaner alternative to doing this in setUp:

        self.temp_subvols.__enter__()
        self.addCleanup(self.temp_subvols.__exit__, None, None, None)

    The primary reason this is bad is explained in the TempSubvolumes
    docblock. It also fails to pass exception info to the __exit__.
    '''

    @functools.wraps(method)
    def decorated(self, *args, **kwargs):
        with TempSubvolumes(sys.argv[0]) as temp_subvols:
            return method(self, temp_subvols, *args, **kwargs)

    return decorated 
Example 2
Project: leapp-repository   Author: oamg   File: utils.py    Apache License 2.0 6 votes vote down vote up
def clean_guard(cleanup_function):
    """
    Decorator to handle any exception going through and running cleanup tasks through the given cleanup_function
    parameter.
    """
    def clean_wrapper(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except Exception:  # Broad exception handler to handle all cases but rethrows
                api.current_logger().debug('Clean guard caught an exception - Calling cleanup function.')
                try:
                    cleanup_function(*args, **kwargs)
                except Exception:  # pylint: disable=broad-except
                    # Broad exception handler to handle all cases however, swallowed, to avoid loosing the original
                    # error. Logging for debuggability.
                    api.current_logger().warn('Caught and swallowed an exception during cleanup.', exc_info=True)
                raise  # rethrow original exception
        return wrapper
    return clean_wrapper 
Example 3
Project: tom-bot   Author: maartenberg   File: helper_functions.py    MIT License 6 votes vote down vote up
def reply_directly(func):
    ''' Decorator to redirect messages to sender if used in group. '''
    @wraps(func)
    def wrapper(bot, message, *args, **kwargs): #pylint: disable=missing-docstring
        result = func(bot, message, *args, **kwargs)
        if not result:
            return
        if message.participant:
            reply = TextMessageProtocolEntity(
                body=result, to=determine_sender(message))
            bot.toLower(reply)
            return
        else:
            return result

    return wrapper

# The following functions are used in react, but do not need the bot's state. 
Example 4
Project: pyblish-win   Author: pyblish   File: _psbsd.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def wrap_exceptions(fun):
    """Decorator which translates bare OSError exceptions into
    NoSuchProcess and AccessDenied.
    """
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except OSError as err:
            # support for private module import
            if (NoSuchProcess is None or AccessDenied is None or
                    ZombieProcess is None):
                raise
            if err.errno == errno.ESRCH:
                if not pid_exists(self.pid):
                    raise NoSuchProcess(self.pid, self._name)
                else:
                    raise ZombieProcess(self.pid, self._name, self._ppid)
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(self.pid, self._name)
            raise
    return wrapper 
Example 5
Project: pyblish-win   Author: pyblish   File: _pslinux.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def wrap_exceptions(fun):
    """Decorator which translates bare OSError and IOError exceptions
    into NoSuchProcess and AccessDenied.
    """
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except EnvironmentError as err:
            # support for private module import
            if NoSuchProcess is None or AccessDenied is None:
                raise
            # ENOENT (no such file or directory) gets raised on open().
            # ESRCH (no such process) can get raised on read() if
            # process is gone in meantime.
            if err.errno in (errno.ENOENT, errno.ESRCH):
                raise NoSuchProcess(self.pid, self._name)
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(self.pid, self._name)
            raise
    return wrapper 
Example 6
Project: pyblish-win   Author: pyblish   File: _pswindows.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def wrap_exceptions(fun):
    """Decorator which translates bare OSError and WindowsError
    exceptions into NoSuchProcess and AccessDenied.
    """
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except OSError as err:
            # support for private module import
            if NoSuchProcess is None or AccessDenied is None:
                raise
            if err.errno in ACCESS_DENIED_SET:
                raise AccessDenied(self.pid, self._name)
            if err.errno == errno.ESRCH:
                raise NoSuchProcess(self.pid, self._name)
            raise
    return wrapper 
Example 7
Project: pyblish-win   Author: pyblish   File: _psosx.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def wrap_exceptions(fun):
    """Decorator which translates bare OSError exceptions into
    NoSuchProcess and AccessDenied.
    """
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except OSError as err:
            # support for private module import
            if (NoSuchProcess is None or AccessDenied is None or
                    ZombieProcess is None):
                raise
            if err.errno == errno.ESRCH:
                if not pid_exists(self.pid):
                    raise NoSuchProcess(self.pid, self._name)
                else:
                    raise ZombieProcess(self.pid, self._name, self._ppid)
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(self.pid, self._name)
            raise
    return wrapper 
Example 8
Project: pyblish-win   Author: pyblish   File: test_functools.py    GNU Lesser General Public License v3.0 6 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 add_dict_attr(f):
            f.dict_attr = {}
            return f
        assign = ('attr',)
        update = ('dict_attr',)
        @functools.wraps(f, assign, update)
        @add_dict_attr
        def wrapper():
            pass
        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 9
Project: pyblish-win   Author: pyblish   File: test_support.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def reap_threads(func):
    """Use this function when threads are being used.  This will
    ensure that the threads are cleaned up even when the test fails.
    If threading is unavailable this function does nothing.
    """
    if not thread:
        return func

    @functools.wraps(func)
    def decorator(*args):
        key = threading_setup()
        try:
            return func(*args)
        finally:
            threading_cleanup(*key)
    return decorator 
Example 10
Project: pyblish-win   Author: pyblish   File: test_fileio.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def ClosedFDRaises(func):
        @wraps(func)
        def wrapper(self):
            #forcibly close the fd before invoking the problem function
            f = self.f
            os.close(f.fileno())
            try:
                func(self, f)
            except IOError as e:
                self.assertEqual(e.errno, errno.EBADF)
            else:
                self.fail("Should have raised IOError")
            finally:
                try:
                    self.f.close()
                except IOError:
                    pass
        return wrapper 
Example 11
Project: xadmin_bugfix   Author: vip68   File: base.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def filter_hook(func):
    tag = func.__name__
    func.__doc__ = "``filter_hook``\n\n" + (func.__doc__ or "")

    @functools.wraps(func)
    def method(self, *args, **kwargs):

        def _inner_method():
            return func(self, *args, **kwargs)

        if self.plugins:
            filters = [(getattr(getattr(p, tag), 'priority', 10), getattr(p, tag))
                       for p in self.plugins if callable(getattr(p, tag, None))]
            filters = [f for p, f in sorted(filters, key=lambda x:x[0])]
            return filter_chain(filters, len(filters) - 1, _inner_method, *args, **kwargs)
        else:
            return _inner_method()
    return method 
Example 12
Project: earlgrey   Author: icon-project   File: message_queue_task.py    Apache License 2.0 6 votes vote down vote up
def message_queue_task(func=None, *, type_=MessageQueueType.RPC, priority=128):
    if func is None:
        return functools.partial(message_queue_task, type_=type_, priority=priority)

    @functools.wraps(func)
    async def _wrapper(*args, **kwargs):
        try:
            return await asyncio.coroutine(func)(*args, **kwargs)
        except Exception as e:
            logging.error(e)
            traceback.print_exc()
            return MessageQueueException(str(e))

    task_attr = {
        MESSAGE_QUEUE_TYPE_KEY: type_,
        MESSAGE_QUEUE_PRIORITY_KEY: priority
    }
    setattr(_wrapper, TASK_ATTR_DICT, task_attr)
    return _wrapper 
Example 13
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 6 votes vote down vote up
def filter_hook(func):
    tag = func.__name__
    func.__doc__ = "``filter_hook``\n\n" + (func.__doc__ or "")

    @functools.wraps(func)
    def method(self, *args, **kwargs):

        def _inner_method():
            return func(self, *args, **kwargs)

        if self.plugins:
            filters = [(getattr(getattr(p, tag), 'priority', 10), getattr(p, tag))
                       for p in self.plugins if callable(getattr(p, tag, None))]
            filters = [f for p, f in sorted(filters, key=lambda x:x[0])]
            return filter_chain(filters, len(filters) - 1, _inner_method, *args, **kwargs)
        else:
            return _inner_method()
    return method 
Example 14
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 6 votes vote down vote up
def filter_hook(func):
    tag = func.__name__
    func.__doc__ = "``filter_hook``\n\n" + (func.__doc__ or "")

    @functools.wraps(func)
    def method(self, *args, **kwargs):

        def _inner_method():
            return func(self, *args, **kwargs)

        if self.plugins:
            filters = [(getattr(getattr(p, tag), 'priority', 10), getattr(p, tag))
                       for p in self.plugins if callable(getattr(p, tag, None))]
            filters = [f for p, f in sorted(filters, key=lambda x:x[0])]
            return filter_chain(filters, len(filters) - 1, _inner_method, *args, **kwargs)
        else:
            return _inner_method()
    return method 
Example 15
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 6 votes vote down vote up
def filter_hook(func):
    tag = func.__name__
    func.__doc__ = "``filter_hook``\n\n" + (func.__doc__ or "")

    @functools.wraps(func)
    def method(self, *args, **kwargs):

        def _inner_method():
            return func(self, *args, **kwargs)

        if self.plugins:
            filters = [(getattr(getattr(p, tag), 'priority', 10), getattr(p, tag))
                       for p in self.plugins if callable(getattr(p, tag, None))]
            filters = [f for p, f in sorted(filters, key=lambda x:x[0])]
            return filter_chain(filters, len(filters) - 1, _inner_method, *args, **kwargs)
        else:
            return _inner_method()
    return method 
Example 16
Project: Flask-pyoidc   Author: zamzterz   File: flask_pyoidc.py    Apache License 2.0 6 votes vote down vote up
def oidc_logout(self, view_func):
        self._logout_view = view_func

        @functools.wraps(view_func)
        def wrapper(*args, **kwargs):
            if 'state' in flask.request.args:
                # returning redirect from provider
                if flask.request.args['state'] != flask.session.pop('end_session_state'):
                    logger.error("Got unexpected state '%s' after logout redirect.", flask.request.args['state'])
                return view_func(*args, **kwargs)

            redirect_to_provider = self._logout()
            if redirect_to_provider:
                return redirect_to_provider

            return view_func(*args, **kwargs)

        return wrapper 
Example 17
Project: elasticsearch-orm   Author: mayankchutani   File: validator.py    GNU General Public License v3.0 6 votes vote down vote up
def type_check(data_type):
    """
    Validates the data type of the value and default value 
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            # type check when called from a constructor of a property type
            if func.__name__ == '__init__':
                value = kwargs.get('default')
            # type check when being called from other functions which have "value" as the first argument
            else:
                value = args[1]
            if not isinstance(value, data_type):
                raise InvalidTypeError(value, data_type)
            return func(*args, **kwargs)
        return wrapper
    return decorator 
Example 18
Project: eve-auth-jwt   Author: rs   File: auth.py    MIT License 6 votes vote down vote up
def requires_token(self, audiences=None, allowed_roles=None):
        """
        Decorator for functions that will be protected with token authentication.

        Token must be provvided either through access_token parameter or Authorization
        header.

        See check_token() method for further details.
        """
        def requires_token_wrapper(f):
            @wraps(f)
            def decorated(*args, **kwargs):
                try:
                    token = request.args['access_token']
                except KeyError:
                    token = request.headers.get('Authorization', '').partition(' ')[2]

                if not self._perform_verification(token, audiences, allowed_roles):
                    abort(401)

                return f(*args, **kwargs)
            return decorated
        return requires_token_wrapper 
Example 19
Project: cape-api-helpers   Author: bloomsburyai   File: input.py    Apache License 2.0 6 votes vote down vote up
def list_document_ids(wrapped):
    """
    Decorator for handling API calls that take as input a list of document ids.
    Calls the wrapped function with the parsed document ids
    selected by the API user.
    """
    @wraps(wrapped)
    def decorated(request, *args, **kwargs):
        if 'documentids' in request['args']:
            if '[' == request['args']['documentids'][0]:
                document_ids = json.loads(request['args']['documentids'])
            else:
                document_ids = request['args']['documentids'].split(',')
        else:
            document_ids = None
        return wrapped(request,*args,**kwargs,document_ids=document_ids)

    return decorated 
Example 20
Project: cape-api-helpers   Author: bloomsburyai   File: input.py    Apache License 2.0 6 votes vote down vote up
def list_saved_reply_ids(wrapped):
    """
    Decorator for handling API calls that take as input a list of saved reply ids.
    Calls the wrapped function with the parsed saved reply ids selected by the
    API user.
    """
    @wraps(wrapped)
    def decorated(request, *args, **kwargs):
        if 'savedreplyids' in request['args']:
            if '[' == request['args']['savedreplyids'][0]:
                saved_reply_ids = json.loads(request['args']['savedreplyids'])
            else:
                saved_reply_ids = request['args']['savedreplyids'].split(',')
        else:
            saved_reply_ids = None
        return wrapped(request, *args, **kwargs, saved_reply_ids=saved_reply_ids)

    return decorated 
Example 21
Project: parsechain   Author: Suor   File: chains.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def has_args(func):
    # Wrap functions from other modules or just mark directly local ones
    if getattr(func, '__module__', None) != __name__:
        wrapper = wraps(func)(lambda *a, **kw: func(*a, **kw))
    else:
        wrapper = func
    wrapper.has_args = True
    return wrapper 
Example 22
Project: navitia_client   Author: leonardbinet   File: client.py    MIT License 5 votes vote down vote up
def make_api_method(func):
    """
    Provides a single entry point for modifying all API methods.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result
    return wrapper 
Example 23
Project: fs_image   Author: facebookincubator   File: extents_to_chunks.py    MIT License 5 votes vote down vote up
def _clone_op_compare(fn):
    @functools.wraps(fn)
    def cmp(self: '_CloneOp', other: '_CloneOp'):
        assert isinstance(other, _CloneOp)
        # We only compare ops within one extent. The tests assume this to
        # justify focusing on single-extent examples, so check it.
        assert self.ref.extent is other.ref.extent
        # All our items are distinct, since `clone.offset` is `inode_offset`,
        # which is strictly increasing in each inode.  We have no business
        # comparing a _CloneOp with itself.
        assert tuple.__ne__(self, other)
        return fn(_clone_op_compare_key(self), _clone_op_compare_key(other))
    return cmp 
Example 24
Project: leapp-repository   Author: oamg   File: pcidevicesscanner.py    Apache License 2.0 5 votes vote down vote up
def aslist(f):
    ''' Decorator used to convert generator to list '''
    @functools.wraps(f)
    def inner(*args, **kwargs):
        return list(f(*args, **kwargs))
    return inner 
Example 25
Project: leapp-repository   Author: oamg   File: systemfacts.py    Apache License 2.0 5 votes vote down vote up
def aslist(f):
    ''' Decorator used to convert generator to list '''
    @functools.wraps(f)
    def inner(*args, **kwargs):
        return list(f(*args, **kwargs))
    return inner 
Example 26
Project: leapp-repository   Author: oamg   File: library.py    Apache License 2.0 5 votes vote down vote up
def aslist(f):
    ''' Decorator used to convert generator to list '''
    @functools.wraps(f)
    def inner(*args, **kwargs):
        return list(f(*args, **kwargs))
    return inner 
Example 27
Project: leapp-repository   Author: oamg   File: rhsm.py    Apache License 2.0 5 votes vote down vote up
def _rhsm_retry(max_attempts, sleep=None):
    """
    A decorator to retry executing a function/method if unsuccessful.

    The function/method execution is considered unsuccessful when it raises StopActorExecutionError.

    :param max_attempts: Maximum number of attempts to execute the decorated function/method.
    :param sleep: Time to wait between attempts. In seconds.
    """
    def impl(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            attempts = 0
            while True:
                attempts += 1
                try:
                    return f(*args, **kwargs)
                except StopActorExecutionError:
                    if max_attempts <= attempts:
                        api.current_logger().warning(
                            'Attempt %d of %d to perform %s failed. Maximum number of retries has been reached.',
                            attempts, max_attempts, f.__name__)
                        raise
                    if sleep:
                        api.current_logger().info(
                            'Attempt %d of %d to perform %s failed - Retrying after %s seconds',
                            attempts, max_attempts, f.__name__, str(sleep))
                        time.sleep(sleep)
                    else:
                        api.current_logger().info(
                            'Attempt %d of %d to perform %s failed - Retrying...', attempts, max_attempts, f.__name__)
        return wrapper
    return impl 
Example 28
Project: apm-python-agent-principle   Author: mozillazg   File: _hook.py    MIT License 5 votes vote down vote up
def func_wrapper(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print('start func')
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print('spent {}s'.format(end - start))
        return result
    return wrapper 
Example 29
Project: apm-python-agent-principle   Author: mozillazg   File: func_wrapper.py    MIT License 5 votes vote down vote up
def func_wrapper(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print('start func')
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print('spent {}s'.format(end - start))
        return result
    return wrapper 
Example 30
Project: apm-python-agent-principle   Author: mozillazg   File: hook.py    MIT License 5 votes vote down vote up
def func_wrapper(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print('start func')
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print('spent {}s'.format(end - start))
        return result
    return wrapper 
Example 31
Project: apm-python-agent-principle   Author: mozillazg   File: hook.py    MIT License 5 votes vote down vote up
def func_wrapper(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print('start func')
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print('spent {}s'.format(end - start))
        return result
    return wrapper 
Example 32
Project: pyblish-win   Author: pyblish   File: signals.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def removeHandler(method=None):
    if method is not None:
        @wraps(method)
        def inner(*args, **kwargs):
            initial = signal.getsignal(signal.SIGINT)
            removeHandler()
            try:
                return method(*args, **kwargs)
            finally:
                signal.signal(signal.SIGINT, initial)
        return inner

    global _interrupt_handler
    if _interrupt_handler is not None:
        signal.signal(signal.SIGINT, _interrupt_handler.original_handler) 
Example 33
Project: pyblish-win   Author: pyblish   File: result.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def failfast(method):
    @wraps(method)
    def inner(self, *args, **kw):
        if getattr(self, 'failfast', False):
            self.stop()
        return method(self, *args, **kw)
    return inner 
Example 34
Project: pyblish-win   Author: pyblish   File: case.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def skip(reason):
    """
    Unconditionally skip a test.
    """
    def decorator(test_item):
        if not isinstance(test_item, (type, types.ClassType)):
            @functools.wraps(test_item)
            def skip_wrapper(*args, **kwargs):
                raise SkipTest(reason)
            test_item = skip_wrapper

        test_item.__unittest_skip__ = True
        test_item.__unittest_skip_why__ = reason
        return test_item
    return decorator 
Example 35
Project: pyblish-win   Author: pyblish   File: case.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def expectedFailure(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except Exception:
            raise _ExpectedFailure(sys.exc_info())
        raise _UnexpectedSuccess
    return wrapper 
Example 36
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _assert_pid_not_reused(fun):
    """Decorator which raises NoSuchProcess in case a process is no
    longer running or its PID has been reused.
    """
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        if not self.is_running():
            raise NoSuchProcess(self.pid, self._name)
        return fun(self, *args, **kwargs)
    return wrapper 
Example 37
Project: pyblish-win   Author: pyblish   File: _pslinux.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def wrap_exceptions_w_zombie(fun):
    """Same as above but also handles zombies."""
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        try:
            return wrap_exceptions(fun)(self)
        except NoSuchProcess:
            if not pid_exists(self.pid):
                raise
            else:
                raise ZombieProcess(self.pid, self._name, self._ppid)
    return wrapper 
Example 38
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'
        @functools.wraps(f)
        def wrapper():
            pass
        self.check_wrapper(wrapper, f)
        return wrapper 
Example 39
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'
        @functools.wraps(f, (), ())
        def wrapper():
            pass
        self.check_wrapper(wrapper, f, (), ())
        self.assertEqual(wrapper.__name__, 'wrapper')
        self.assertEqual(wrapper.__doc__, None)
        self.assertFalse(hasattr(wrapper, 'attr')) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def system_must_validate_cert(f):
    """Skip the test on TLS certificate validation failures."""
    @functools.wraps(f)
    def dec(*args, **kwargs):
        try:
            f(*args, **kwargs)
        except IOError as e:
            if "CERTIFICATE_VERIFY_FAILED" in str(e):
                raise unittest.SkipTest("system does not contain "
                                        "necessary certificates")
            raise
    return dec 
Example 41
Project: pyblish-win   Author: pyblish   File: test_ssl.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def skip_if_broken_ubuntu_ssl(func):
    if hasattr(ssl, 'PROTOCOL_SSLv2'):
        @functools.wraps(func)
        def f(*args, **kwargs):
            try:
                ssl.SSLContext(ssl.PROTOCOL_SSLv2)
            except ssl.SSLError:
                if (ssl.OPENSSL_VERSION_INFO == (0, 9, 8, 15, 15) and
                    platform.linux_distribution() == ('debian', 'squeeze/sid', '')):
                    raise unittest.SkipTest("Patched Ubuntu OpenSSL breaks behaviour")
            return func(*args, **kwargs)
        return f
    else:
        return func 
Example 42
Project: pyblish-win   Author: pyblish   File: test_fileio.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def ClosedFD(func):
        @wraps(func)
        def wrapper(self):
            #forcibly close the fd before invoking the problem function
            f = self.f
            os.close(f.fileno())
            try:
                func(self, f)
            finally:
                try:
                    self.f.close()
                except IOError:
                    pass
        return wrapper 
Example 43
Project: pyblish-win   Author: pyblish   File: _mock_backport.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __getattr__(self, name):
        if name in {'_mock_methods', '_mock_unsafe'}:
            raise AttributeError(name)
        elif self._mock_methods is not None:
            if name not in self._mock_methods or name in _all_magics:
                raise AttributeError("Mock object has no attribute %r" % name)
        elif _is_magic(name):
            raise AttributeError(name)
        if not self._mock_unsafe:
            if name.startswith(('assert', 'assret')):
                raise AttributeError(name)

        result = self._mock_children.get(name)
        if result is _deleted:
            raise AttributeError(name)
        elif result is None:
            wraps = None
            if self._mock_wraps is not None:
                # XXXX should we get the attribute without triggering code
                # execution?
                wraps = getattr(self._mock_wraps, name)

            result = self._get_child_mock(
                parent=self, name=name, wraps=wraps, _new_name=name,
                _new_parent=self
            )
            self._mock_children[name]  = result

        elif isinstance(result, _SpecState):
            result = create_autospec(
                result.spec, result.spec_set, result.instance,
                result.parent, result.name
            )
            self._mock_children[name]  = result

        return result 
Example 44
Project: pyblish-win   Author: pyblish   File: _mock_backport.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def decorate_callable(self, func):
        if hasattr(func, 'patchings'):
            func.patchings.append(self)
            return func

        @wraps(func)
        def patched(*args, **keywargs):
            extra_args = []
            entered_patchers = []

            exc_info = tuple()
            try:
                for patching in patched.patchings:
                    arg = patching.__enter__()
                    entered_patchers.append(patching)
                    if patching.attribute_name is not None:
                        keywargs.update(arg)
                    elif patching.new is DEFAULT:
                        extra_args.append(arg)

                args += tuple(extra_args)
                return func(*args, **keywargs)
            except:
                if (patching not in entered_patchers and
                    _is_started(patching)):
                    # the patcher may have been started, but an exception
                    # raised whilst entering one of its additional_patchers
                    entered_patchers.append(patching)
                # Pass the exception to __exit__
                exc_info = sys.exc_info()
                # re-raise the exception
                raise
            finally:
                for patching in reversed(entered_patchers):
                    patching.__exit__(*exc_info)

        patched.patchings = [self]
        return patched 
Example 45
Project: pyblish-win   Author: pyblish   File: _mock_backport.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __call__(self, f):
        if isinstance(f, type):
            return self.decorate_class(f)
        @wraps(f)
        def _inner(*args, **kw):
            self._patch_dict()
            try:
                return f(*args, **kw)
            finally:
                self._unpatch_dict()

        return _inner 
Example 46
Project: pyblish-win   Author: pyblish   File: contextlib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def contextmanager(func):
    """@contextmanager decorator.

    Typical usage:

        @contextmanager
        def some_generator(<arguments>):
            <setup>
            try:
                yield <value>
            finally:
                <cleanup>

    This makes this:

        with some_generator(<arguments>) as <variable>:
            <body>

    equivalent to this:

        <setup>
        try:
            <variable> = <value>
            <body>
        finally:
            <cleanup>

    """
    @wraps(func)
    def helper(*args, **kwds):
        return GeneratorContextManager(func(*args, **kwds))
    return helper 
Example 47
Project: flaskit   Author: elston   File: utils.py    MIT License 5 votes vote down vote up
def login_required_admin(func):

    @wraps(func)
    def decorated_view(*args, **kwargs):
        # ..
        if not current_user.is_admin:
            return current_app.login_manager.unauthorized()
        return func(*args, **kwargs)
    return decorated_view 
Example 48
Project: xadmin_bugfix   Author: vip68   File: base.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def inclusion_tag(file_name, context_class=Context, takes_context=False):
    def wrap(func):
        @functools.wraps(func)
        def method(self, context, nodes, *arg, **kwargs):
            _dict = func(self, context, nodes, *arg, **kwargs)
            from django.template.loader import get_template, select_template
            cls_str = str if six.PY3 else basestring
            if isinstance(file_name, Template):
                t = file_name
            elif not isinstance(file_name, cls_str) and is_iterable(file_name):
                t = select_template(file_name)
            else:
                t = get_template(file_name)

            _dict['autoescape'] = context.autoescape
            _dict['use_l10n'] = context.use_l10n
            _dict['use_tz'] = context.use_tz
            _dict['admin_view'] = context['admin_view']

            csrf_token = context.get('csrf_token', None)
            if csrf_token is not None:
                _dict['csrf_token'] = csrf_token
            nodes.append(t.render(_dict))

        return method
    return wrap 
Example 49
Project: drydock   Author: airshipit   File: policy.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, f):
        @functools.wraps(f)
        def secure_handler(slf, req, resp, *args, **kwargs):
            ctx = req.context

            policy_engine = ctx.policy_engine

            self.logger.debug("Enforcing policy %s on request %s" %
                              (self.action, ctx.request_id))

            if policy_engine is not None and policy_engine.authorize(
                    self.action, ctx):
                return f(slf, req, resp, *args, **kwargs)
            else:
                if ctx.authenticated:
                    slf.info(
                        ctx,
                        "Error - Forbidden access - action: %s" % self.action)
                    slf.return_error(
                        resp,
                        falcon.HTTP_403,
                        message="Forbidden",
                        retry=False)
                else:
                    slf.info(ctx, "Error - Unauthenticated access")
                    slf.return_error(
                        resp,
                        falcon.HTTP_401,
                        message="Unauthenticated",
                        retry=False)

        return secure_handler 
Example 50
Project: Mastering-Python-Networking-Second-Edition   Author: PacktPublishing   File: chapter9_9.py    MIT License 5 votes vote down vote up
def background(f):
    """Decorator that runs the wrapped function as a background task. It is
    assumed that this function creates a new resource, and takes a long time
    to do so. The response has status code 202 Accepted and includes a Location
    header with the URL of a task resource. Sending a GET request to the task
    will continue to return 202 for as long as the task is running. When the task
    has finished, a status code 303 See Other will be returned, along with a
    Location header that points to the newly created resource. The client then
    needs to send a DELETE request to the task resource to remove it from the
    system."""
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        # The background task needs to be decorated with Flask's
        # copy_current_request_context to have access to context globals.
        @copy_current_request_context
        def task():
            global background_tasks
            try:
                # invoke the wrapped function and record the returned
                # response in the background_tasks dictionary
                background_tasks[id] = make_response(f(*args, **kwargs))
            except:
                # the wrapped function raised an exception, return a 500
                # response
                background_tasks[id] = make_response(internal_server_error())

        # store the background task under a randomly generated identifier
        # and start it
        global background_tasks
        id = uuid.uuid4().hex
        background_tasks[id] = Thread(target=task)
        background_tasks[id].start()

        # return a 202 Accepted response with the location of the task status
        # resource
        return jsonify({}), 202, {'Location': url_for('get_task_status', id=id)}
    return wrapped

# g is the context request object from Flask