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?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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)
</code>
<code>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) </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@app.route('/hello', methods=['GET', 'POST'])
def hello():
return "test"
</code>
<code>@app.route('/hello', methods=['GET', 'POST']) def hello(): return "test" </code>
@app.route('/hello', methods=['GET', 'POST'])
def hello():
    return "test"

The following does not return a response:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@app.route('/hello', methods=['GET', 'POST'])
def hello():
hello_world()
</code>
<code>@app.route('/hello', methods=['GET', 'POST']) def hello(): hello_world() </code>
@app.route('/hello', methods=['GET', 'POST'])
def hello():
    hello_world()

You mean to say…

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@app.route('/hello', methods=['GET', 'POST'])
def hello():
return hello_world()
</code>
<code>@app.route('/hello', methods=['GET', 'POST']) def hello(): return hello_world() </code>
@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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@app.route("/hello", methods=["GET", "POST"])
def hello():
if request.method == "POST":
return hello_world()
# missing return statement here
</code>
<code>@app.route("/hello", methods=["GET", "POST"]) def hello(): if request.method == "POST": return hello_world() # missing return statement here </code>
@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):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@app.route("/hello")
def hello():
try:
return database_hello()
except DatabaseError as e:
app.logger.exception(e)
return "Can't say hello."
</code>
<code>@app.route("/hello") def hello(): try: return database_hello() except DatabaseError as e: app.logger.exception(e) return "Can't say hello." </code>
@app.route("/hello")
def hello():
    try:
        return database_hello()
    except DatabaseError as e:
        app.logger.exception(e)
        return "Can't say hello."

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@app.route('/hello', methods=['GET', 'POST'])
def hello():
return Response(hello_world(), status=200)
</code>
<code>@app.route('/hello', methods=['GET', 'POST']) def hello(): return Response(hello_world(), status=200) </code>
@app.route('/hello', methods=['GET', 'POST'])
def hello():
    return Response(hello_world(), status=200)

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@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)
</code>
<code>@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) </code>
@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)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật