Python Flask 视图返回错误“视图函数没有返回响应”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18211942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:13:34  来源:igfitidea点击:

Flask view return error "View function did not return a response"

pythonflask

提问by

I have a view that calls a function to get the response. However, it gives the error View function did not return a response. How do I fix this?

我有一个调用函数来获取响应的视图。但是,它给出了错误View function did not return a response。我该如何解决?

from flask import Flask
app = Flask(__name__)

def hello_world():
    return 'test'

@app.route('/hello', methods=['GET', 'POST'])
def hello():
    hello_world()

if __name__ == '__main__':
    app.run(debug=True)

When I try to test it by adding a static value rather than calling the function, it works.

当我尝试通过添加静态值而不是调用函数来测试它时,它起作用了。

@app.route('/hello', methods=['GET', 'POST'])
def hello():
    return "test"

采纳答案by Mark Hildreth

The following does not return a response:

以下不返回响应:

@app.route('/hello', methods=['GET', 'POST'])
def hello():
    hello_world()

You mean to say...

你的意思是说...

@app.route('/hello', methods=['GET', 'POST'])
def hello():
    return hello_world()

Note the addition of returnin this fixed function.

注意return在这个固定函数中的添加。

回答by davidism

No matter what code executes in a view function, the view must return a value that Flask recognizes as a response. If the function doesn't return anything, that's equivalent to returning None, which is not a valid response.

无论在视图函数中执行什么代码,视图都必须返回一个 Flask 识别为响应的值。如果该函数不返回任何内容,则相当于返回None,这不是有效的响应。

In addition to omitting a returnstatement completely, another common error is to only return a response in some cases. If your view has different behavior based on an ifor a try/except, you need to ensure that every branch returns a response.

除了return完全省略语句之外,另一个常见错误是仅在某些情况下返回响应。如果您的视图基于 anif或 a try/具有不同的行为except,则需要确保每个分支都返回响应。

This incorrect example doesn't return a response on GET requests, it needs a return statement after the if:

这个不正确的示例不会返回对 GET 请求的响应,它需要在 之后的 return 语句if

@app.route("/hello", methods=["GET", "POST"])
def hello():
    if request.method == "POST":
        return hello_world()

    # missing return statement here

This correct example returns a response on success and failure (and logs the failure for debugging):

这个正确的例子返回成功和失败的响应(并记录调试失败):

@app.route("/hello")
def hello():
    try:
        return database_hello()
    except DatabaseError as e:
        app.logger.exception(e)
        return "Can't say hello."