本文介绍了Flask中的API-返回JSON但HTML异常破坏了我的JSON客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异常破坏了我的JSON客户端.我想对输出进行JSON化.

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&amp;cmd=resource&amp;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 错误瓶中的处理程序.

一个简单的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客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:10
查看更多