简体   繁体   中英

Flask view return error "View function did not return a response"

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?

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)

When I try to test it by adding a static value rather than calling the function, it works.

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

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.

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

I'm sorry, but my answer is not for this question. Lately I came here browsing the same error message used in the title, but any of the previous messages answared my problem with my Flask API.

To return a json, yaml, xml, etc. that was retrived from another API using the requests module you need to return the text of the response and and not the class Response that the requests module use to represent any response. For example:

# ❌ 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

In this error message Flask complains that the function did not return a valid response . The emphasis on response suggests that it is not just about the function returning a value, but a valid flask.Response object which can print a message, return a status code etc. So that trivial example code could be written like this:

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

Or even better if wrapped in the try-except clause:

@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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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