问题:from flask_restful reqparse 自定义的help内容无法显示
代码如下:
from flask_restful import reqparse
class EquipmentStaticView(views.MethodView):
def ret_init(self):
return {
"message": '',
"status": '',
"count": 0,
"data": []
}
@swag_from('./api_doc/demo.yml')
def post(self, *args, **kwargs):
r = self.ret_init()
parser = reqparse.RequestParser(bundle_errors=True)
add = parser.add_argument
add('eqmt_no', type=str,required=True, help="emp_no is requied")
add('eqmt_name', type=str)
add('spce', type=str)
add('counts', type=int,help='must be an int')
add('manufacturer', type=str)
add('supplier', type=str)
add('maintain_dept', type=str)
add('line', type=str)
add('sys_tp', type=str)
add('major', type=str)
add('measure_unit', type=str)
add('use_date', type=lambda x: datetime.datetime.strptime(x, '%Y-%m-%d'),help='must be format like:2020-01-01')
add('install_addr', type=str)
add('dept', type=str)
args = parser.parse_args()
logger.info(args)
try:
x = EquipmentStatic(**args)
session.add(x)
session.flush()
session.commit()
schema = EquipmentStaticSchema()
result = schema.dump(x)
r["data"].append(result)
r["count"] = 1
r["status"] = 201
r["message"] = "创建成功"
except Exception as e:
session.rollback()
r["message"] = e.__repr__()
r["status"] = 400
return jsonify(r), 400
return jsonify(r), 201
预期是在当post时 前端传来的参数错误里返回 add(‘eqmt_no’, type=str,required=True, help=“emp_no is requied”) 这里 help中定议的提示信息,
但是上面代码返回的并不如预期,而是返回:400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
经过一烦查看源码后。终于找到问题目的所在了。
先从函数parser.add_argument一层层的往下找
args = parser.parse_args()
-- 以下是
def parse_args(self, req=None, strict=False, http_error_code=400):
...省略一些源码... 看这里 当有错误时,是调用 flask_restful.abort
if errors:
flask_restful.abort(http_error_code, message=errors)
if strict and req.unparsed_arguments:
raise exceptions.BadRequest('Unknown arguments: %s'
% ', '.join(req.unparsed_arguments.keys()))
return namespace
接下来看一下 flask_restful.abort
def abort(http_status_code, **kwargs):
"""Raise a HTTPException for the given http_status_code. Attach any keyword
arguments to the exception for later processing.
"""
#noinspection PyUnresolvedReferences
try:
original_flask_abort(http_status_code)
except HTTPException as e:
if len(kwargs):
e.data = kwargs
raise
从代码来看,abort是将错误存到了 exception 的data中了。并将异常抛出,所以解决办法就是,处理这个异常,并将异常中的data返给前端。
try:
args = parser.parse_args()
except Exception as e:
logger.info(e)
r.update(e.data)
return jsonify(r),400
看下效果吧:
{
"count": 0,
"data": [],
"message": {
"eqmt_no": "emp_no is requied"
},
"status": ""
}