python中wraps是什么意思_【Python】Flask中@wraps的使用

先说总结,白话来讲,@wraps相当于是装饰器的装饰器。

python内置的方法使用解释,看起很复杂的样子┓( ´∀` )┏

def wraps(wrapped,

assigned = WRAPPER_ASSIGNMENTS,

updated = WRAPPER_UPDATES):

"""Decorator factory to apply update_wrapper() to a wrapper function

Returns a decorator that invokes update_wrapper() with the decorated

function as the wrapper argument and the arguments to wraps() as the

remaining arguments. Default arguments are as for update_wrapper().

This is a convenience function to simplify applying partial() to

update_wrapper().

"""

return partial(update_wrapper, wrapped=wrapped,

assigned=assigned, updated=updated)

下面举个栗子:

from functools import wraps

# 用户角色权限确认

def permission_required():

def decorator(f):

#@wraps(f)

def decorated_function():

return ‘this is decorated function‘

return decorated_function

return decorator

# 管理员权限确认

def admin_required(f):

return permission_required()(f)

if __name__==‘__main__‘:

def test_func():

return ‘this is test function‘

print(admin_required(test_func))

不用@wraps时,打印出来是酱婶儿的

.decorator..decorated_function at 0x00000000030411E0>

使用之后看起来清爽了很多

通过对比结果,@wraps的作用猜出来个大概。

使用之后它返回的是参数test_func方法的地址。也就是说,如果你想使用参数方法的一些属性,就需要使用@wraps了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python Flask提供了多种身份验证方式,常用的有以下几种: 1. 基本认证(Basic Authentication):通过用户名和密码进行验证,使用HTTP的Authorization头字段传递。 2. Token认证(Token Authentication):通过在每个请求传递一个token来验证用户身份。token通常是一串加密的字符串,用于识别用户。 3. OAuth认证(OAuth Authentication):OAuth是一种授权协议,允许用户通过第三方服务进行身份验证和授权。 下面是一个使用基本认证的示例代码: ```python from flask import Flask, request, Response from functools import wraps app = Flask(__name__) def check_auth(username, password): return username == 'admin' and password == 'secret' def authenticate(): return Response( 'Unauthorized', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'} ) def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return authenticate() return f(*args, **kwargs) return decorated @app.route('/') @requires_auth def index(): return "Hello, authenticated user!" if __name__ == '__main__': app.run() ``` 在上面的代码,我们定义了一个check_auth函数,用于验证用户名和密码是否正确。authenticate函数用于返回401错误码和WWW-Authenticate头,提示用户需要登录。requires_auth是一个装饰器函数,用于验证请求是否经过身份验证。如果没有经过身份验证,则调用authenticate函数。 在路由函数使用@requires_auth装饰器,表示该路由需要经过身份验证才能访问。如果用户提供了正确的用户名和密码,则返回"Hello, authenticated user!"。如果没有提供正确的用户名和密码,则返回401错误码和WWW-Authenticate头,提示用户登录。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值