Minimal Flask Web Application

Beginner

Introduction

Flask is a micro web framework for building web applications in Python. It's designed to be simple and lightweight, allowing developers to quickly create web applications without imposing too many restrictions or dependencies.

Eager to get started? In the first lab, we will explore how to create a minimal Flask application.

A Minimal Application

In this step, you will create a simple Flask application.

  1. Open the hello.py file and first import the Flask class. An instance of this class will be our WSGI application.
from flask import Flask
  1. Next we create an instance of this class. The first argument is the name of the applicationโ€™s module or package. __name__ is a convenient shortcut for this that is appropriate for most cases. This is needed so that Flask knows where to look for resources such as templates and static files.
app = Flask(__name__)
  1. We then use the route() decorator to tell Flask what URL should trigger our hello_world function. The function is called view function. It returns the message we want to display in the userโ€™s browser. The default content type is HTML, so HTML in the string will be rendered by the browser.
@app.route("/")
def hello_world():
    return "Hello, World!"
  1. Creating a main entry point of the script for starting the minimal application at port 5000, set the value of the debug variable to True. By enabling the debug mode, the server will automatically reload if code changes, and will show an interactive debugger in the browser if an error occurs during a request.
if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)
  1. To run the application, first using the following commands to launched the Flask application in the terminal:
python3 hello.py

Then open the "Web 5000" tab located at the top of the interface, refresh the page, and you should see the message Hello, World!.

Summary

In this lab, we have implemented a simple Flask application that successfully displays "Hello world" on port 5000. This is the beginning of learning Flask, after that, there will be more complex knowledge waiting for us to master.

Other Tutorials you may like