Sunday, September 4, 2022

[SOLVED] Flask hello.py basic app not running?

Issue

when I enter python hello.py in the command line, I get another bash prompt. I'm not sure what could be the problem since I'm able to run a virtualenv and when I check which version of flask I have the latest version, >>> '0.10.1' installed.

Opals-MacBook-Pro:~ opalkale$ cd myproject
Opals-MacBook-Pro:myproject opalkale$ ls
hello.py    venv
Opals-MacBook-Pro:myproject opalkale$ . venv/bin/activate
(venv)Opals-MacBook-Pro:myproject opalkale$ python hello.py
(venv)Opals-MacBook-Pro:myproject opalkale$ 

The code for hello.py looks like:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

    if __name__ == "__main__":
            app.run()

This code was taken from: http://flask.pocoo.org/docs/quickstart/#quickstart


Solution

Your file does not match the example in the documentation. You've placed the if __name__ == '__main__': block inside the definition of hello().

Whitespace is significant in Python. It needs to be placed outside the function definition (i.e., aligned all the way to the left). Doing so will execute the if when the script is run. The way it exists now, you would need to import the hello module and call the hello function. That isn't what you want. Fix the indentation and you will be all set.



Answered By - dirn
Answer Checked By - Marie Seifert (WPSolving Admin)