本文整理汇总了Python中functools.wraps方法的典型用法代码示例。如果您正苦于以下问题:Python functools.wraps方法的具体用法?Python functools.wraps怎么用?Python functools.wraps使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类functools
的用法示例。
在下文中一共展示了functools.wraps方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: requires_auth
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def requires_auth(func):
"""Decorator to note which object methods require authorization."""
@wraps(func)
def auth_wrapper(self, *args, **kwargs):
auth = False
if hasattr(self, '_session'):
auth = (self._session.auth or
self._session.headers.get('Authorization'))
if auth:
return func(self, *args, **kwargs)
else:
from .models import GitHubError
# Mock a 401 response
r = generate_fake_error_response(
'{"message": "Requires authentication"}'
)
raise GitHubError(r)
return auth_wrapper
示例2: requires_basic_auth
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def requires_basic_auth(func):
"""Specific (basic) authentication decorator.
This is used to note which object methods require username/password
authorization and won't work with token based authorization.
"""
@wraps(func)
def auth_wrapper(self, *args, **kwargs):
if hasattr(self, '_session') and self._session.auth:
return func(self, *args, **kwargs)
else:
from .models import GitHubError
# Mock a 401 response
r = generate_fake_error_response(
'{"message": "Requires username/password authentication"}'
)
raise GitHubError(r)
return auth_wrapper
示例3: requires_app_credentials
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def requires_app_credentials(func):
"""Require client_id and client_secret to be associated.
This is used to note and enforce which methods require a client_id and
client_secret to be used.
"""
@wraps(func)
def auth_wrapper(self, *args, **kwargs):
client_id, client_secret = self._session.retrieve_client_credentials()
if client_id and client_secret:
return func(self, *args, **kwargs)
else:
from .models import GitHubError
# Mock a 401 response
r = generate_fake_error_response(
'{"message": "Requires username/password authentication"}'
)
raise GitHubError(r)
return auth_wrapper
示例4: s3_request
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def s3_request(func: Callable):
"""
Wrapper function for s3 requests in order to create more helpful error
messages.
"""
@wraps(func)
def wrapper(url: str, *args, **kwargs):
try:
return func(url, *args, **kwargs)
except ClientError as exc:
if int(exc.response["Error"]["Code"]) == 404:
raise FileNotFoundError("file {} not found".format(url))
else:
raise
return wrapper
示例5: token_required
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def token_required(func):
"""
检查是否携带token,如果token未携带或无效将直接返回错误,否则将username保存到g.username中
"""
from everyclass.server.user import service as user_service
@functools.wraps(func)
def wrapped(*args, **kwargs):
token = request.headers.get("X-API-Token")
if not token:
return generate_error_response(None, STATUS_CODE_TOKEN_MISSING)
username = user_service.get_username_from_jwt(token)
if not username:
return generate_error_response(None, STATUS_CODE_INVALID_TOKEN)
g.username = username
return func(*args, **kwargs)
return wrapped
示例6: login_required
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def login_required(func):
"""检查用户是否已登录,如未登录则返回错误"""
@functools.wraps(func)
def wrapped(*args, **kwargs):
try:
ut, uid = get_ut_uid()
if ut == UTYPE_GUEST:
return generate_error_response(None, STATUS_CODE_PERMISSION_DENIED, "您需要登录才能进行此操作")
except NotImplementedError:
return generate_error_response(None, STATUS_CODE_PERMISSION_DENIED, "检测身份时遇到未知错误")
g.user_id = uid
return func(*args, **kwargs)
return wrapped
示例7: oidc_logout
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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
示例8: requires_token
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
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
示例9: wrap_exception
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def wrap_exception(func):
"""
Allow Device discovery methods to return None instead of raising an
exception.
"""
@functools.wraps(func)
def the_func(*args, **kwargs):
"""
Returns result of calling ``func`` on ``args``, ``kwargs``.
Returns None if ``func`` raises :exc:`DeviceNotFoundError`.
"""
try:
return func(*args, **kwargs)
except DeviceNotFoundError:
return None
return the_func
示例10: translateable_docstring
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def translateable_docstring(cls):
@functools.wraps(cls.config_complete)
def config_complete(self, *args, **kwargs):
for command, func in get_commands(cls).items():
@functools.wraps(func)
def replacement(*args, **kwargs):
return func(self, *args, **kwargs)
replacement.__doc__ = self.strings["_cmd_doc_" + command]
setattr(self, command, replacement)
self.__doc__ = self.strings["_cls_doc"]
return self.config_complete._old_(self, *args, **kwargs)
config_complete._old_ = cls.config_complete
cls.config_complete = config_complete
for command, func in get_commands(cls).items():
cls.strings["_cmd_doc_" + command] = inspect.getdoc(func)
cls.strings["_cls_doc"] = inspect.getdoc(cls)
return cls
示例11: requires_roles
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def requires_roles(required_roles):
'''
Takes in a list of roles and checks whether the user
has access to those role
'''
def check_roles(view_function):
@wraps(view_function)
def decorated_function(*args, **kwargs):
def names(role):
return role.name
if not all(r in map(names, current_user.roles) for r in required_roles):
flash('You do not have sufficient permissions to do that', 'alert alert-danger')
return redirect(request.args.get('next') or '/')
return view_function(*args, **kwargs)
return decorated_function
return check_roles
示例12: extractor_auth_required
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def extractor_auth_required():
'''
Ensures that current_user is an extractor with access to the correct department
'''
def check_extractor(view_function):
@wraps(view_function)
def decorated_function(*args, **kwargs):
username = request.authorization.username
password = request.authorization.password
found_extractor = Extractor.query.filter_by(username=username).first()
if not found_extractor:
return ("No extractor with that username!", 401)
if not found_extractor.check_password(password):
return ("Extractor authorization failed!", 401)
return view_function(*args, **kwargs)
return decorated_function
return check_extractor
示例13: add_arg_scope
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def add_arg_scope(func):
"""Decorates a function with args so it can be used within an arg_scope.
Args:
func: function to decorate.
Returns:
A tuple with the decorated function func_with_args().
"""
@functools.wraps(func)
def func_with_args(*args, **kwargs):
current_scope = _current_arg_scope()
current_args = kwargs
key_func = (func.__module__, func.__name__)
if key_func in current_scope:
current_args = current_scope[key_func].copy()
current_args.update(kwargs)
return func(*args, **current_args)
_add_op(func)
return func_with_args
示例14: deprecated_test
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def deprecated_test(test: Callable) -> Callable:
"""Marks a test as using deprecated functionality.
Ensures the test is executed within the `pytest.deprecated_call()` context.
Args:
test: The test.
Returns:
The decorated test.
"""
@functools.wraps(test)
def decorated_test(*args, **kwargs) -> Any:
with pytest.deprecated_call():
test(*args, **kwargs)
return decorated_test
示例15: refresh_on_error
# 需要导入模块: import functools [as 别名]
# 或者: from functools import wraps [as 别名]
def refresh_on_error(
self,
error_class=Exception,
error_callback=None,
retry_argument='is_retry'
):
""" Decorator to handle errors and retries """
if error_callback and not callable(error_callback):
raise TypeError("error_callback must be callable")
def true_decorator(func):
""" Actual func wrapper """
@wraps(func)
def wrapped(*args, **kwargs):
""" Actual error/retry handling """
try:
return func(*args, **kwargs)
except error_class: # pylint: disable=broad-except
self.refresh()
if error_callback:
error_callback()
if retry_argument:
kwargs[retry_argument] = True
return func(*args, **kwargs)
return wrapped
return true_decorator