39

我有一个调用函数来获取响应的视图。但是,它给出了错误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)

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

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

3 回答 3

57

以下不返回响应:

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

你的意思是说...

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

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

于 2013-08-13T14:34:26.177 回答
10

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

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

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

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

    # missing return statement here

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

@app.route("/hello")
def hello():
    try:
        return database_hello()
    except DatabaseError as e:
        app.logger.exception(e)
        return "Can't say hello."
于 2019-04-10T14:40:37.217 回答
0

在此错误消息中,Flask 抱怨function did not return a valid response. 对响应的强调表明它不仅仅是关于返回值的函数,而是一个flask.Response可以打印消息、返回状态代码等的有效对象。因此,可以这样编写简单的示例代码:

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

如果包含在 try-except 子句中,甚至更好:

@app.route('/hello', methods=['GET', 'POST'])
def hello():
    try:
        result = hello_world()
    except Exception as e:
        return Response('Error: {}'.format(str(e)), status=500)
    return Response(result, status=200)
于 2021-11-30T09:20:05.443 回答