Flask view return error “View function did not return a response”

后端 未结 2 1504
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 04:00

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?



        
相关标签:
2条回答
  • 2020-11-22 04:25

    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 return in this fixed function.

    0 讨论(0)
  • 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.

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

    This incorrect example doesn't return a response on GET requests, it needs a return statement after the 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."
    
    0 讨论(0)
提交回复
热议问题