【发布时间】:2018-06-30 06:08:12
【问题描述】:
我有烧瓶宁静的应用程序。我试图传递无效的 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 过渡//EN"
"http://www.w3.org/TR/html4/loose.dtd"> TypeError:is not JSON serializable // Werkzeug Debugger
【问题讨论】:
-
我使用 method_decorators 将这些装饰器附加到资源类?\
-
糟糕,我把那些与常规方法视图混淆了。
标签: flask flask-restful