wtforms验证器抛出的异常信息
整体目录结构(只是测试)
代码实现
error.py
from flask import request, json
from werkzeug.exceptions import HTTPException
class APIException(HTTPException):
"""
继承HTTPException,并重写get_body,get_headers方法
使其返回restful统一异常处理
"""
code = 500
msg = 'sorry internal error'
error_code = 999
def __init__(self, msg=None, code=None, error_code=None, headers=None):
if code:
self.code = code
if msg:
self.msg = msg
if error_code:
self.error_code = error_code
super(APIException, self).__init__(msg, None)
def get_body(self, environ=None):
body = dict(
error_code = self.error_code,
msg = self.msg,
request = request.method + ' ' + self.get_url_no_parm()
)
text = json.dumps(body)
return text
def get_headers(self, environ=None):
return [('Content-Type', 'application/json')]
@staticmethod
def get_url_no_parm():
full_path = str(request.path)
return full_path
error_code.py
from libs.error import APIException
class ParameterException(APIException):
"""参数异常类"""
code = 400
msg = 'invalid parameter'
error_code = 1000
base.py
from flask import request
from wtforms import Form
from libs.error_code import ParameterException
class BaseForm(Form):
def __init__(self):
"""从request.json中获取请求参数"""
data = request.json
super(BaseForm, self).__init__(data=data)
def validate_for_api(self):
"""抛出自定义异常"""
valid = super(BaseForm, self).validate()
if not valid:
raise ParameterException(msg=self.errors)
return self
user_forms.py
from wtforms.fields import simple
from wtforms import validators
from wtforms.validators import DataRequired
from verication.base import BaseForm
class Myvalidators(object):
'''自定义验证规则'''
def __init__(self,message):
self.message = message
def __call__(self, form, field):
if not isinstance(field.data,str):
raise validators.ValidationError(self.message)
class Index(BaseForm):
username = simple.StringField(validators=[
DataRequired(message="用户名不能为空"),
Myvalidators(message='value必须是字符串')
])
password = simple.StringField(validators=[
DataRequired(message="密码不能为空"),
Myvalidators(message='value必须是字符串')
])
app.py
from flask import Flask
from verication.user_form import Index
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
forms = Index().validate_for_api()
if forms:
return 'hello word'
else:
return 'error'
if __name__ == '__main__':
app.run(debug=True)