Flask restful 对 post 请求的初始 json 验证

Flask restful initial json validation for the post request

我有烧瓶 restful 申请。我试图传递无效的 json 并且我的服务器向用户抛出 html 标签。

如何向用户抛出漂亮的错误消息说 json 无效。? POST 方法

class MyView(Resource):

    def post(self):
        try:
            signup_data = request.get_json(force=True)
            country_code = signup_data['country_code']

数据通过(无效json)

{
    "country_code": "hello",
    "country_code": "hello"
}

错误信息

File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line
1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)   
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py",
line 484, in wrapper
return self.make_response(data, code, headers=headers)   
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py",
line 513, in make_response
resp = self.representations[mediatype](data, *args, **kwargs)   
File "/usr/local/lib/python2.7/dist-packages/flask_restful/representations/json.py",
line 21, in output_json
dumped = dumps(data, **settings) + "\n"   
File "/usr/lib/python2.7/json/__init__.py", line 251, in dumps
sort_keys=sort_keys, **kw).encode(obj)   File "/usr/lib/python2.7/json/encoder.py", line 209, in encode
chunks = list(chunks)   
File "/usr/lib/python2.7/json/encoder.py", line 442, in _iterencode
o = _default(o)   
File "/usr/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable") 
TypeError: <Response 29 bytes [200 OK]> is not JSON serializable

输出给用户

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"> TypeError: <Response 29 bytes [200 OK]> is not JSON serializable // Werkzeug Debugger

您可以 try - except 读取 json 的行输入,捕获 TypeError 并在那里抛出一个很好的错误消息:

try:
    signup_data = request.get_json(force=True)
except TypeError:
    return jsonify(message="Invalid json input"), 400

使用from flask import jsonify导入jsonify