本文整理匯總了Python中six.wraps方法的典型用法代碼示例。如果您正苦於以下問題:Python six.wraps方法的具體用法?Python six.wraps怎麽用?Python six.wraps使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類six
的用法示例。
在下文中一共展示了six.wraps方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: template
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def template(action):
"""Handle template actions.
.. py:decorator:: template
Checks if the kind is 'template' and processes else default processing.
"""
def decorator(func):
@six.wraps(func)
def handler(self, obj, namespace=None):
apiver, kind, _ = validator.validate(obj)
if kind == 'Template':
return self._process_template(apiver, kind, action, obj, namespace)
else:
return func(self, obj, namespace)
return handler
return decorator
示例2: return_none_on_failure
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def return_none_on_failure(f):
try:
# Python 3
fname = f.__qualname__
except AttributeError:
fname = f.__name__
@six.wraps(f)
def _return_none_on_failure(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as e:
LOG.critical("Unexpected error while calling %s: %s",
fname, e, exc_info=True)
return _return_none_on_failure
# Retry with exponential backoff for up to 1 minute
示例3: queryapi
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def queryapi(version, kind, nsarg=True):
"""Make Query API.
.. py:decorator:: queryapi
Creates a named query api.
"""
def decorator(func):
@six.wraps(func)
def handler(self, namespace=DEFAULT_NAMESPACE):
if not nsarg:
namespace = None
url = self._generate_url(api_version=version,
kind=kind,
namespace=namespace)
return Query(self, url)
return handler
return decorator
示例4: negate
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def negate(func):
"""
Given a comparison function ``func``, build and return a comparison function that negates
the result of ``func``.
:param func: a comparison function taking three arguments
:return: a comparison function taking three arguments
"""
@wraps(func)
def negated(left, comparator, right):
return not func(left, comparator, right)
return negated
#: This class enumerates all available comparators.
#: In order to add a comparator to this module, add a suitable member to COMPARATORS
#: and suitable entries to COMPARATOR_FUNCTIONS and COMPARATOR_DESCRIPTIONS.
示例5: interprocess_locked
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def interprocess_locked(path):
"""Acquires & releases a interprocess lock around call into
decorated function."""
lock = InterProcessLock(path)
def decorator(f):
@six.wraps(f)
def wrapper(*args, **kwargs):
with lock:
return f(*args, **kwargs)
return wrapper
return decorator
示例6: authenticated
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def authenticated(blocking=True):
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
user = None
auth = request.headers.get('Authorization')
if auth and len(auth) >= 7:
sid = auth[7:] # 'Bearer ' prefix
session = sessions.get(sid)
if session and session.get('user_id'):
user = get_user(session['user_id'])
if user:
user.sid = sid
if blocking and not user:
raise ApiException('unauthorized', status_code=401)
res = f(user=user, *args, **kwargs)
return res
return wrapper
return decorator
示例7: mock_response
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def mock_response(method, uri, data, errors=None, warnings=None, pagination=None):
def wrapper(fn):
@six.wraps(fn)
@hp.activate
def inner(*args, **kwargs):
body = {'data': data}
if errors is not None:
body['errors'] = errors
if warnings is not None:
body['warnings'] = warnings
if pagination is not None:
body['pagination'] = pagination
hp.reset()
hp.register_uri(method, re.compile('.*' + uri + '$'), json.dumps(body))
return fn(*args, **kwargs)
return inner
return wrapper
示例8: retry
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def retry(exceptions, interval=1, retries=3, backoff_rate=2):
if retries < 1:
raise ValueError(_('Retries must be greater than or '
'equal to 1 (received: %s). ') % retries)
def _decorator(f):
@six.wraps(f)
def _wrapper(*args, **kwargs):
r = tenacity.Retrying(
before_sleep=tenacity.before_sleep_log(LOG, logging.DEBUG),
after=tenacity.after_log(LOG, logging.DEBUG),
stop=tenacity.stop_after_attempt(retries),
reraise=True,
retry=tenacity.retry_if_exception_type(exceptions),
wait=tenacity.wait_exponential(
multiplier=interval, min=0, exp_base=backoff_rate))
return r.call(f, *args, **kwargs)
return _wrapper
return _decorator
示例9: token_required
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def token_required(self, func=None, callback=None):
"""Decorator for endpoints which require a verified user."""
# logger.debug("token_required received func={!r}, callback={!r}", func, callback)
if func is None:
# called with optional arguments; return value will be called without, so pass them through
return functools.partial(self.token_required, callback=callback)
@six.wraps(func)
def decorator(request, *args, **kwargs):
userinfo = self.check_token(request)
kwargs['userinfo'] = userinfo
args = (request,) + args
if callback is not None:
# logger.debug("calling {!r} with args={!r} and kwargs={!r}", callback, args, kwargs)
callback(*args, **kwargs)
# logger.debug("calling {!r} with args={!r} and kwargs={!r}", func, args, kwargs)
return func(*args, **kwargs)
return decorator
示例10: serialized_endpoint
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def serialized_endpoint(*_callbacks):
"""Decorator which wraps an endpoint by applying callbacks to the results then serializing to JSON.
First, the decorated function is called and must return a `defer.Deferred`. The callbacks supplied
to the decorator are then applied followed by any callbacks supplied as keyword arguments to the
decorated function. The result is then serialized and returned in the response (with
``Content-Type`` set to ``application/json``).
"""
def decorator(func):
@six.wraps(func)
def wrapped(request, *args, **kwargs):
callbacks = kwargs.pop('callbacks', [])
# logger.debug("in wrapped:\nargs: {!r}\nkwargs: {!r}", args, kwargs)
deferred_list = func(*args, **kwargs)
for callback in list(_callbacks) + callbacks:
deferred_list.addCallback(callback)
deferred_list.addCallback(json.dumps, default=stethoscope.utils.json_serialize_datetime)
request.setHeader('Content-Type', 'application/json')
return deferred_list
return wrapped
return decorator
示例11: translate_server_exception
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def translate_server_exception(method):
"""Transforms the exception for the instance.
Note: keeps its traceback intact.
"""
@six.wraps(method)
def wrapper(self, ctx, instance_id, *args, **kwargs):
try:
res = method(self, ctx, instance_id, *args, **kwargs)
return res
except nova_exception.ClientException as e:
if isinstance(e, nova_exception.NotFound):
raise exception.InstanceNotFound(instance_id=instance_id)
elif isinstance(e, nova_exception.BadRequest):
raise exception.InvalidInput(reason=six.text_type(e))
else:
raise exception.ManilaException(e)
return wrapper
示例12: set_timeout
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def set_timeout(timeout):
"""Timeout decorator for unit test methods.
Use this decorator for tests that are expected to pass in very specific
amount of time, not common for all other tests.
It can have either big or small value.
"""
def _decorator(f):
@six.wraps(f)
def _wrapper(self, *args, **kwargs):
self.useFixture(fixtures.Timeout(timeout, gentle=True))
return f(self, *args, **kwargs)
return _wrapper
return _decorator
示例13: _ensure_wrappability
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def _ensure_wrappability(fn):
"""Make sure `fn` can be wrapped cleanly by functools.wraps."""
# Handle "builtin_function_or_method", "wrapped_descriptor", and
# "method-wrapper" types.
unwrappable_types = (type(sum), type(object.__init__), type(object.__call__))
if isinstance(fn, unwrappable_types):
# pylint: disable=unnecessary-lambda
wrappable_fn = lambda *args, **kwargs: fn(*args, **kwargs)
wrappable_fn.__name__ = fn.__name__
wrappable_fn.__doc__ = fn.__doc__
wrappable_fn.__module__ = '' # These types have no __module__, sigh.
wrappable_fn.__wrapped__ = fn
return wrappable_fn
# Otherwise we're good to go...
return fn
示例14: __init__
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def __init__(self, scoped_selector, evaluate):
self._scoped_selector = scoped_selector
self._evaluate = evaluate
scoped_selector_parts = self._scoped_selector.split('/')
self._scopes = scoped_selector_parts[:-1]
self._selector = scoped_selector_parts[-1]
self._configurable = _REGISTRY.get_match(self._selector)
if not self._configurable:
_raise_unknown_reference_error(self)
def reference_decorator(fn):
if self._scopes:
@six.wraps(fn)
def scoping_wrapper(*args, **kwargs):
with config_scope(self._scopes):
return fn(*args, **kwargs)
return scoping_wrapper
return fn
self._scoped_configurable_fn = _decorate_fn_or_cls(
reference_decorator, self.configurable.fn_or_cls, True)
示例15: keras_test
# 需要導入模塊: import six [as 別名]
# 或者: from six import wraps [as 別名]
def keras_test(func):
"""Function wrapper to clean up after TensorFlow tests.
# Arguments
func: test function to clean up after.
# Returns
A function wrapping the input function.
"""
@six.wraps(func)
def wrapper(*args, **kwargs):
output = func(*args, **kwargs)
if K.backend() == 'tensorflow':
K.clear_session()
return output
return wrapper