Flask视图返回错误“查看函数未返回响应”

时间:2013-08-13 14:32:49

标签: python flask

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

2 个答案:

答案 0 :(得分:41)

以下内容未返回回复:

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

你的意思是说......

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

请注意在此固定功能中添加了return

答案 1 :(得分:1)

无论在视图函数中执行什么代码,视图都必须返回a value that Flask recognizes as a response。如果该函数未返回任何内容,则等同于返回None,这不是有效的响应。

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

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

@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."