tornado权限装饰器demo

# -*- coding: utf-8 -*-
import tornado.ioloop
import tornado.web
# 利用装饰器, 实现主页和登录页任何人可以访问,系统后台只有超级管理员,运维可以访问


def _access_check(_object):
    """仅为demo,结合业务逻辑进行验证"""
    role = _object.get_argument("role", "")
    check_type = _object.__check_type__
    if role not in check_type:
        raise tornado.web.HTTPError(403)


def need_check(**kwargs):
    def wrapper(handler):
        if kwargs.get("check_type") and kwargs.get("check"):
            handler.__check_type__ = kwargs["check_type"]
        handler.access_check = _access_check
        return handler
    return wrapper


class BaseHandler(tornado.web.RequestHandler):
    """中间件基类"""
    def prepare(self):
        if hasattr(self, "__check_type__"):
            self.access_check()
            

class IndexHandler(BaseHandler):
    def get(self):
        self.write("来到首页")
        
        
@need_check(check=True, check_type=["superuser", "operations"])
class AdminHandler(BaseHandler):
    def get(self):
        self.write("来到系统后台")
        

@need_check(check=False)  # 强迫症开发者
class LoginHandler(BaseHandler):
    def get(self):
        self.write("来到登录页面")


def make_app():
    return tornado.web.Application([
        (r"/", IndexHandler),
        (r"/admin", AdminHandler),
        (r"/login", LoginHandler),
    ])


if __name__ == "__main__":
    app = make_app()
    app.listen(8899)
    tornado.ioloop.IOLoop.current().start()

访问: http://127.0.0.1:8899/admin?role=superuser
返回:来到系统后台

访问: http://127.0.0.1:8899/admin?role=user
返回: 403: Forbidden

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值