Flask 中的 API——返回 JSON 但 HTML 异常破坏了我的 JSON 客户端 [英] API in Flask--returns JSON but HTML exceptions break my JSON client
问题描述
HTML 中返回的异常破坏了我的 JSON 客户端.我想对这个输出进行 jsonify.
exceptions returned in HTML break my JSON client. I want to jsonify this output.
更多细节:我有一个视图函数,它是这个 api 应用程序的端点.
More detail: i have a view function which an endpoint of this api app.
如您所见,此函数以 json 格式返回结果.
As you can see, this function returns the result in json.
@app.route('/route1')
def api_route1():
if user_id in request.args:
k1 = request.args['user_id']
return flask.jsonify(recs=some_function(k1))
else:
return "no valid user_id supplied"
问题,未处理的异常在 HTML 中,例如,
The problem, unhandled exception are in HTML, e.g.,
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>TypeError: 'NoneType' object is not iterable // Werkzeug Debugger</title>
<link rel="stylesheet"
href="?__debugger__=yes&cmd=resource&f=style.css"
type="text/css">
这破坏了我的 json 客户端.HTML 格式显然是默认格式,但我不知道如何选择退出它并指定 jsonified 异常(理想情况下 jsonify 任何返回的甚至是标题).
This breaks my json client. The HTML format is clearly a default, but i don't know how to opt out of it and specify jsonified exceptions (and ideally jsonify anything returned even headers).
我怀疑我需要的东西在优秀的 Flask 文档中,但我找不到.
I suspect what i need is somewhere in the excellent Flask documentation, but i can't find it.
推荐答案
你应该定义 HTTP error烧瓶中的处理程序.
You should define HTTP error handlers in flask.
一个简单的 JSON 返回 404 处理程序可能如下所示:
A simple JSON returing 404 handler might look something like this:
@app.errorhandler(404)
def page_not_found(e):
return flask.jsonify(error=404, text=str(e)), 404
有了这个,您将能够检查客户端上的 data.error
,如果它存在,您可以使用 data.text 获取错误文本(错误作为 e
是 werkzeug.exceptions.NotFound
,其字符串表示为404:未找到").
With this you will be able to check for data.error
on the client and if it exists you can get the error text with data.text (the error passed as e
is werkzeug.exceptions.NotFound
whose string representation is "404: Not Found").
这篇关于Flask 中的 API——返回 JSON 但 HTML 异常破坏了我的 JSON 客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!