Flask为post请求重新进行初始json验证

时间:2018-01-21 13:56:23

标签: flask flask-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&#34; - // W3C // DTD HTML 4.01 Transitional // EN&#34;
  &#34; http://www.w3.org/TR/html4/loose.dtd&#34;&GT;                  TypeError:&lt;响应29字节[200 OK]&gt;不是JSON可序列化的// Werkzeug Debugger                      

1 个答案:

答案 0 :(得分:1)

您可以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