Flask Hello World

Outline

What you need to get started

Note: All terminal commands in Windows for Python follow python <your command>.
Note: All terminal commands in Linux for Python follow python3 <your command>.

Setting up

# For Windows and Linux
mkdir flask-work
cd flask-work

Pip installs

Next, we will need to install the necessary dependencies to run our application For the hello world program, all we need is the Flask module. To install this, run:

# For Windows
pip install flask

# For Linux
pip3 install flask

Creating the file

# For Windows
echo "" > hello-world.py

# For Linux
touch hello-world.py

Writing the code

Open your newly created hello-world.py file in the text editor of your choice and paste in the following code.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

That's it! The above code is all you need to serve content in a browser. Obviously, Flask can do a ton more than saying "Hello World" in a browser. Take this site, for instance, it was written completely with Flask as the backend! Pretty cool right :) Alright, let's run this thing!

Running the code

Back in your terminal, you will want to run the following command to start up the server.

# For Windows
python hello-world.py

# For Linux
python3 hello-world.py

Now you can visit http://127.0.0.1:5000/ in your browser!

The above command executes the python file and spins up a development server. The development server will display stack traces in the browser whenever there are code errors. This is useful for debugging and speeding up development. In the future, I will hopefully write an article on how to set up a production environment that can handle lots of requests per second and do it securely without showing your viewers any error traces.

Comments

Login to Add comments.