【问题标题】:Flask view return error "View function did not return a response"Flask 视图返回错误“视图函数没有返回响应”
【发布时间】:2022-01-22 12:36:41
【问题描述】:

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

【问题讨论】:

    标签: python flask


    【解决方案1】:

    以下不返回响应:

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

    你的意思是……

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

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

    【讨论】:

      【解决方案2】:

      无论在视图函数中执行什么代码,视图都必须返回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."
      

      【讨论】:

        【解决方案3】:

        在此错误消息中,Flask 抱怨 function did not return a valid response.对 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)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-12-26
          相关资源
          最近更新 更多