[SOLVED] ValueError in Flask: View function did not return a response

Flask is one of the most used frameworks by the web developers community. One of most faced error is the ValueError: View function did not return a response.

We can avoid this error if we examine the code properly. We know that a function should return something or object but when it doesn't return anything to function you will get the error.

We can solve this error in two methods.

Let's see how we can solve this with one example:

Method 1

from flask import Flask

app = Flask(__name__)
def function_hola():
    return 'test'
@app.route('/hello.html', methods=['GET', 'POST'])
def hola():
    function_hola()

if __name__ == '__main__':
    app.run(debug=True)

Value Error

Here check the 11th line where the function hola is not returning anything so we get ValueError: View function did not return a response. To avoid these errors we should make our code minimal with well-defined functions.

Value Error

from flask import Flask

app = Flask(__name__)

def function_hola():
    return 'test'

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

if __name__ == '__main__':
    app.run(debug=True)

If we return something to the function hola() gives the responsive output so we may get rid of that error.

Method 2

We can also solve this by returning none, check this example below:

def hola():
    pass
a = hola()
print (a)

This will return none as the output. We can avoid ValueError: View function did not return a response by returning none value.

Both Method 1 and Method 2 can be used based on the needs of our code.

What I would suggest, for further debugging is, using Flask's logging facility in order to print in the console the values of the variables that you are using for manipulation in order to track down the error.

Reason

One of our functions returns None and not that a return statement is missing and you need to ensure that every branch returns a response.


Further Reading

  1. How do you fix UnboundLocalError in Python?
  2. [SOLVED] psql: FATAL database 'root' does not exist error
  3. What is Atatus APM and its Benefits?

Monitor your software stack for free with Atatus.

Start your free trial
OR
Request a Demo

Free 14-day trial. No credit card required. Cancel anytime.

Ready to see actionable data?

Avail Atatus features for 14 days free-trial. No credit card required. Instant set-up.