返回顶部

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()

 

其实要想给类视图添加装饰器,其实方法非常的简单,类视图中有一个类属性

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

 

把新添加的装饰器添加到类视图的装饰列表中

decorators = [authorized, pro]

 

在这里authorized装饰器我给了权限,而pro没有给权限,最后验证不会通过,是否能达到我们想要的效果呢,启动项目

好了关于类视图的所有操作,到此介绍完了

 

posted @ 2018-02-02 11:17  Crazymagic  阅读(406)  评论(0编辑  收藏  举报