繁体   English   中英

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

[英]Flask view return error "View function did not return a response"

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

以下不返回响应:

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

你的意思是说...

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

请注意在此固定函数中添加了return

无论在视图函数中执行什么代码,视图都必须返回一个 Flask 识别为响应的值 如果函数没有返回任何内容,则相当于返回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."

对不起,我的回答不是针对这个问题的。 最近我来到这里浏览标题中使用的相同错误消息,但之前的任何消息都回答了我的 Flask API 问题。

要返回使用requests模块从另一个 API 检索的 json、yaml、xml 等,您需要返回响应的文本,而不是requests模块用来表示任何响应的类Response 例如:

# ❌ Wrong way to respond a response ❌
@server.route('/')
def home():
    import requests
    cats_response = requests.get('https://catfact.ninja/fact')

    return cats_response # 👈❌ Returns a class requests.models.Response
# ✔️ Right way to respond a response ✔️
@server.route('/')
def home():
    import requests
    cats_response = requests.get('https://catfact.ninja/fact')

    return cats_response.text # 👈✔️ Returns a string of the cats information

在此错误消息中,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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM