Search code examples
pythonpython-3.xflaskpycharm

Flask Python - basic program does not work


I wrote this super basic application. It runs but does not do a thing:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def Index():
    return "<h1>Hello!</h1>"


if __name__ == "__name__":
    app.run(debug=True)

The console shows:

C:\Users\TalT\PycharmProjects\FlaskBeginners\venv\Scripts\python.exe C:/Users/TalT/PycharmProjects/FlaskBeginners/MyFirstWebPage.py

Process finished with exit code 0

I work on Win10, PyCharm 2019.3.3 and Python 3.7 . I don't understand where is the problem? Is it a python issue or maybe project configuration?


Solution

  • Your problem is:

    if __name__ == "__name__":
    

    Must change to:

    if __name__ == '__main__':
    

    To start a flask app you have 2 easy different ways.

    1. Rename your main file to app.py or wsgi.py and go to path of the file in terminal and type flask run. In this way, if you want to run app in debug mode, In the same path, type set FLASK_ENV=development in terminal (Windows) and then write flask run.

    Tip: In this way, you must delete the following code from your project:

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

    2. Write your code in a python file (name is not matter) for example with main.py name write like this:

    from flask import Flask
    
    app = Flask(__name__)
    app.config['DEBUG']=True
    
    @app.route('/')
    def Index():
        return '<h1>Hello!</h1>'
    
    
    if __name__ == '__main__':
        app.run()
    

    And run the application by running this command in the path of your file: python main.py . Remember, add this code app.config['DEBUG']=True only if you want to run your code in debug mode.