Search code examples
pythonflaskhttp-status-code-500

Internal Server Error when running Flask App


Really appreciate your help! I am a beginner to Flask, playing with it to build out APIs.

When executing the below code snippet and run the code in vs-code terminal, it appears to run the app on http://127.0.0.1:5000/.

However, when I click-through the URL within the terminal - to launch the URL in the browser and expect to display 'Hello World' - it displays 'Internal Server Error' on the page. It then prints 'ERROR in app: Exception on / [GET].

Code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    print('Hello World!')

app.run(port=5000)

Terminal:

WKMGB0671549:REST-APIs josshepp$ python3 app_copy.py
 * Serving Flask app "app_copy" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Hello World!
[2019-07-11 08:51:50,920] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
    return self.finalize_request(rv)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 1967, in finalize_request
    response = self.make_response(rv)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/flask/app.py", line 2097, in make_response
    "The view function did not return a valid response. The"
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
127.0.0.1 - - [11/Jul/2019 08:51:50] "GET / HTTP/1.1" 500 -

Solution

  • Your view function does not return a valid response. In short, return "Hello World!" instead of printing it:

    @app.route('/')
    def home():
        return 'Hello World!'
    

    Flask automatically converts several types of return vales into Response for you, but you can read up on how they convert (link):

    The return value from a view function is automatically converted into a response object for you. If the return value is a string it’s converted into a response object with the string as response body, a 200 OK status code and a text/html mimetype.

    If the term view function is confusing, it is described by flask as (link):

    A view function is the code you write to respond to requests to your application. Flask uses patterns to match the incoming request URL to the view that should handle it. The view returns data that Flask turns into an outgoing response.