Tornado 参数校验

Python 2017-06-07 22:34 暂无评论

tornado 做数据校验的时候有点麻烦,特别是我接收和输出都是 JSON 这里用到的是 jsonschema 来做校验数据,如果参数不符则报错。

import functools
from tornado.web import RequestHandler, Application
from tornado.escape import json_decode, json_encode
from tornado.web import asynchronous
from tornado import gen

# 校验 json 数据
def Validates(Schema):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(self, *args, **kwargs):
            try:
                validate(json_decode(self.request.body), Schema)
                return func(self, *args, **kwargs)
            except:
                self.set_status(500)
                self.write({"success": False, "message": "params error", "status": 500})
        return wrapper
    return decorator

class PlanHandler(BaseHandler):
    @asynchronous
    @gen.coroutine
    def get(self, *args, **kwargs):
        self.write("hello")

    @Validates(PlanSchema)
    @asynchronous
    @gen.coroutine
    def post(self, *args, **kwargs):
        params = json_decode(self.request.body)
        self.write(params)

再贴一个无参数的装饰器。有参数的要多一个函数。

# 校验令牌
def ValiAuth(func):
    def decorator(self, *args, **kwargs):
        if json_decode(self.request.body)["auth"] != self.auth:
            self.set_status(401)
            self.write({"success": False, "message": "Auth error", "status": 401})
        else:
            return func(self, *args, **kwargs)
    return decorator
暂无评论