本文整理匯總了Python中decorator.decorator方法的典型用法代碼示例。如果您正苦於以下問題:Python decorator.decorator方法的具體用法?Python decorator.decorator怎麽用?Python decorator.decorator使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類decorator
的用法示例。
在下文中一共展示了decorator.decorator方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: with_error_settings
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def with_error_settings(**new_settings):
"""
TODO.
Arguments:
**new_settings: TODO
Returns:
"""
@decorator.decorator
def dec(f, *args, **kwargs):
old_settings = np.geterr()
np.seterr(**new_settings)
ret = f(*args, **kwargs)
np.seterr(**old_settings)
return ret
return dec
示例2: deprecated
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def deprecated(version, version_removed):
'''This is a decorator which can be used to mark functions
as deprecated.
It will result in a warning being emitted when the function is used.'''
def __wrapper(func, *args, **kwargs):
'''Warn the user, and then proceed.'''
code = six.get_function_code(func)
warnings.warn_explicit(
"{:s}.{:s}\n\tDeprecated as of JAMS version {:s}."
"\n\tIt will be removed in JAMS version {:s}."
.format(func.__module__, func.__name__,
version, version_removed),
category=DeprecationWarning,
filename=code.co_filename,
lineno=code.co_firstlineno + 1
)
return func(*args, **kwargs)
return decorator(__wrapper)
示例3: call_stack
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def call_stack(func, *args, **kwargs):
"""This decorator is used to get the method name and
arguments and save it to self.stack. The data from
self.stack is predominantly used to save recepies.
"""
func_sig = dict()
func_self = args[0]
func_sig["function"] = func.__name__
bound_args = inspect.signature(func).bind(*args, **kwargs)
bound_args.apply_defaults()
func_arguments = dict(bound_args.arguments)
del func_arguments["self"]
func_sig["args"] = func_arguments
func_self._stack.append(func_sig)
return func(*args, **kwargs)
示例4: submit_result_to_codespeed
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def submit_result_to_codespeed(func):
"""
Decorator which marks a pytest benchmark function with "submit_result_to_codespeed" marker.
"""
# NOTE: functools.wraps doesn't work well enough under Python 2 so we need to use decorator
# package
def wrapped_function(func, *args, **kwargs):
if isinstance(args[0], BenchmarkFixture):
benchmark = args[0]
elif "benchmark" in kwargs:
benchmark = kwargs["benchmark"]
else:
raise ValueError('Unable to detect "benchmark" kwarg')
benchmark.submit_result_to_codespeed = True
return func(*args, **kwargs)
return decorator.decorator(wrapped_function, func)
# Register a custom marker
示例5: enforce_driver_supported
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def enforce_driver_supported():
@decorator.decorator
def wrapper(func, *args, **kwargs):
cluster_template = args[1]
cluster_distro = cluster_template.cluster_distro
if not cluster_distro:
try:
cli = clients.OpenStackClients(pecan.request.context)
image_id = cluster_template.image_id
image = api_utils.get_openstack_resource(cli.glance().images,
image_id,
'images')
cluster_distro = image.get('os_distro')
except Exception:
pass
cluster_type = (cluster_template.server_type,
cluster_distro,
cluster_template.coe)
driver.Driver.get_driver(*cluster_type)
return func(*args, **kwargs)
return wrapper
示例6: enforce_volume_driver_types_update
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def enforce_volume_driver_types_update():
@decorator.decorator
def wrapper(func, *args, **kwargs):
cluster_template_ident = args[1]
patch = args[2]
cluster_template = api_utils.get_resource('ClusterTemplate',
cluster_template_ident)
try:
cluster_template_dict = api_utils.apply_jsonpatch(
cluster_template.as_dict(), patch)
except api_utils.JSONPATCH_EXCEPTIONS as e:
raise exception.PatchError(patch=patch, reason=e)
_enforce_volume_driver_types(cluster_template_dict)
return func(*args, **kwargs)
return wrapper
示例7: enforce_wsgi
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def enforce_wsgi(api_name, act=None):
"""This is a decorator to simplify wsgi action policy rule check.
:param api_name: The collection name to be evaluate.
:param act: The function name of wsgi action.
example:
from magnum.common import policy
class ClustersController(rest.RestController):
....
@policy.enforce_wsgi("cluster", "delete")
@wsme_pecan.wsexpose(None, types.uuid_or_name, status_code=204)
def delete(self, cluster_ident):
...
"""
@decorator.decorator
def wrapper(fn, *args, **kwargs):
action = "%s:%s" % (api_name, (act or fn.__name__))
enforce(pecan.request.context, action,
exc=exception.PolicyNotAuthorized, action=action)
return fn(*args, **kwargs)
return wrapper
示例8: requires_properties
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def requires_properties(properties):
@decorator
def _requires_properties(func, *args, **kwargs):
params = util.map_parameters_in_fn_call(args, kwargs, func)
obj = params.get('self')
if obj is None:
raise Exception('This decorator only works on instance methods')
missing = [p for p in properties if getattr(obj, p) is None]
if len(missing):
raise ValueError('{} requires {} to be set, missing: {}'
.format(func.__name__, properties, missing))
return func(*args, **kwargs)
return _requires_properties
示例9: valid_kwargs
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def valid_kwargs(*valid_args):
# This decorator checks if argument passed as **kwargs to a function are
# present in valid_args.
#
# Typically, valid_kwargs is used when we want to distinguish between
# None and omitted arguments and we still want to validate the argument
# list.
#
# Example usage:
#
# @valid_kwargs('opt_arg1', 'opt_arg2')
# def my_func(self, mandatory_arg1, mandatory_arg2, **kwargs):
# ...
#
@decorator
def func_wrapper(func, *args, **kwargs):
argspec = inspect.getargspec(func)
for k in kwargs:
if k not in argspec.args[1:] and k not in valid_args:
raise TypeError(
"{f}() got an unexpected keyword argument "
"'{arg}'".format(f=inspect.stack()[1][3], arg=k))
return func(*args, **kwargs)
return func_wrapper
示例10: reconfirm_auth
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def reconfirm_auth(func, *args, **kwargs):
'''
A decorator to require the user to reconfirm their login. Useful for sensitive pages.
'''
from allura.lib.plugin import AuthenticationProvider
if request.POST.get('password'):
if AuthenticationProvider.get(request).validate_password(c.user, request.POST['password']):
session['auth-reconfirmed'] = datetime.utcnow()
session.save()
kwargs.pop('password', None)
else:
c.form_errors['password'] = 'Invalid password.'
allowed_timedelta = timedelta(seconds=asint(config.get('auth.reconfirm.seconds', 60)))
last_reconfirm = session.get('auth-reconfirmed', datetime.min)
if datetime.utcnow() - last_reconfirm <= allowed_timedelta:
return func(*args, **kwargs)
else:
return render({}, 'jinja', "allura:templates/reconfirm_auth.html")
示例11: _journal
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def _journal(journaler):
"""Journaler to decorate API functions.
"""
@decorator.decorator
def decorated(func, *args, **kwargs):
"""Decorated function."""
action = getattr(
func, 'journal_action', func.__name__.strip('_'))
resource = getattr(
func, 'journal_resource', func.__module__.strip('_'))
transaction_id = _get_tx_id()
journaler.log_begin(transaction_id, resource, action, args)
try:
result = func(*args, **kwargs)
journaler.log_end(transaction_id, resource, action, args, result)
except Exception as err:
# we log execption of API and raise again
journaler.log_abort(transaction_id, resource, action, args, err)
raise err
return result
return decorated
示例12: render_statement
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def render_statement(method, self, statement, *args, **kwargs):
"""
Pre-render a statement template prior to wrapped function execution.
This decorator expects to act as wrapper on functions which
takes statements as the second argument.
"""
if kwargs.pop('template', True):
statement = self.template_render(
statement,
context=kwargs.pop('context', {}),
by_name=False,
)
return method(self, statement, *args, **kwargs)
示例13: memoize
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def memoize(f, refresh_keyword='mrefresh'):
"""
Memoize decorator. The refresh keyword is the keyword
used to bypass the cache (in the function call).
"""
f.mcache = {}
f.mrefresh_keyword = refresh_keyword
return decorator.decorator(_memoize, f)
示例14: decode_arg
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def decode_arg(name, decoder, allow_optional=False):
"""Create a decorator that applies `decoder` to argument `name`."""
@decorator
def new_f(f, *args, **kwargs):
call_args = inspect.getcallargs(f, *args, **kwargs)
call_args[name] = (
decoder(call_args[name], allow_optional=True)
if allow_optional
else decoder(call_args[name])
)
return f(**call_args)
return new_f
示例15: encode_res
# 需要導入模塊: import decorator [as 別名]
# 或者: from decorator import decorator [as 別名]
def encode_res(encoder):
"""Create a decorator that applies `encoder` to the return value of the
decorated function.
"""
@decorator
async def new_f(f, *args, **kwargs):
res = await f(*args, **kwargs)
return encoder(res)
return new_f