4- Sanic在类视图上加装饰器
sanic类视图的写法
主要就是继承HTTPMethodView的类
其余的就是什么请求,定义什么方法就好
from sanic import Sanic from sanic.response import text, json from sanic.views import HTTPMethodView app = Sanic(__name__) class ViewWithDecorator(HTTPMethodView): async def get(self, request): return text('Hello I have a decorator') async def post(self, request): return text('Hello I have a decorator') app.add_route(ViewWithDecorator.as_view(), '/') if __name__ == '__main__': app.run()
其实要想给类视图添加装饰器,其实方法非常的简单,类视图中有一个类属性
1 | decorators = [ ] |
只需把装饰器中的方法添加进去就行,下面简单的写一个用户带有用户认证的权限的装饰器,代码如下:
def authorized(*args): def decorator(f): async def decorated_function(request, *args, **kwargs): is_authorized = False if is_authorized: # the user is authorized. # run the handler method and return the response response = await f(request, *args, **kwargs) return response else: return json({'status': 'not_authorized'}) return decorated_function if args: return decorator(*args) else: return decorator
注意上面的代码和传统装饰器的不同之处了吗,在下面多了这样的一段代码
if args: return decorator(*args) else: return decorator
这个是必须要写的不然会报错的,下面我们来运行一下,这里的is_authorized = False,所以用户没有权限,请求就不会成功。
同样的用postman测试post请求也是同样的结果
接下来再把认证函数中的is_authorized = True,重启一下项目,再来测试一下,这下用户就有请求权限了,看看结果是否是我们想要的呢
好了,测试成功。
那么可不可在添加一层装饰器呢,答案显然也是可以的,添加的装饰器如下:
def pro(*args): def decorator(f): async def decorated_function(request, *args, **kwargs): pro_authorized = False if pro_authorized: # the user is authorized. # run the handler method and return the response response = await f(request, *args, **kwargs) return response else: return json({'status': 'pro not auth success'}) return decorated_function if args: return decorator(*args) else: return decorator
把新添加的装饰器添加到类视图的装饰列表中
1 | decorators = [authorized, pro] |
在这里authorized装饰器我给了权限,而pro没有给权限,最后验证不会通过,是否能达到我们想要的效果呢,启动项目
好了关于类视图的所有操作,到此介绍完了
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理