a shot of dev knowledge

Related tags

How to create a "Hello, world" app using Python Flask

Flask is a Python microframework for building web applications and APIs – its simple architecture allows you to get running in seconds.

In this shot, you will learn how to create a Flask app that displays hello-world.

Setting up the virtual environment

Click the run button below to activate the terminal. After the default commands in the terminal get executed, run these commands in the terminal.

python3 -m venv venv
. venv/bin/activate

Note: If running locally, you may need to install venv. Run the command below to install venv.

$ python3 -m venv venv # unix
$ py -3 -m venv venv # windows

Creating your first Flask app

Run the widget below and install Flask into the virtual environment using:

pip install Flask

The widget contains an app.py file. This file:

  1. Imports the Flask class from the flask package. Flask is used to create instances of web applications.
  2. Initializes the app as an instance of Flask.
  3. Sets a function that responds to the index route, ‘/’, and displays 'Hello, World!`
  4. Runs the app if the current script being executed is app.py.
from flask import Flask
app = Flask(__name__)

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

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

Running the hello-world app

A Flask application has a single entry point. For the terminal to know the entry point of your app, you need to set a FLASK_APP environment variable. These commands have already been set in the widget below, simply run the widget and check the output tab.

export FLASK_APP=app.py

Now, run your flask app using:

flask run
from flask import Flask
app = Flask(__name__)

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

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

What does if __name__ == "__main__" mean?

The conditional check if __name__ == "__main__" simply checks if the script being executed is app.py.

Say you created a script called utils.py that only contains print(__name__). If you import utils.py into app.py and run app.py, the print statement from utils.py will output utils, which is the name of the file.

In the case of app.py the name variable will be “main”.

Wrap up

Flask allows you to set up a web application with minimal configuration. These applications range from Model-View-Controller (MVC) apps to APIs.

In this shot, you learned how to set up a web application using the Flask framework.

Related tags

RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring