Labs ICT
โญ Pro Login

What is Flask?

The micro-framework that does a lot with a little.

4 min read | Flask Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

What is Flask?

Flask is a micro web framework written in Python. Created by Armin Ronacher as part of the Pocoo project, it has grown into one of the most popular frameworks for building web applications and APIs. The key word here is "micro" โ€” not because it's limited, but because it keeps the core simple and unopinionated. You decide what tools and libraries to use rather than having them forced on you.

Under the hood, Flask is built on two solid foundations: Werkzeug for handling WSGI (Web Server Gateway Interface) and Jinja2 for template rendering. This means you get battle-tested components without extra complexity. Companies like Netflix, Reddit, Lyft, and Pinterest trust Flask in production, which speaks volumes about its reliability.

So why pick Flask over something like Django? It comes down to three things: simplicity, flexibility, and the learning experience. Flask lets you start small and scale up as needed. There's no admin panel you'll never use, no ORM you didn't ask for. You build exactly what you need, nothing more. This makes it perfect for REST APIs, quick prototypes, and even full-scale web applications.

Installing Flask

Before you install Flask, make sure you have Python 3.7 or newer installed on your machine. You can check your Python version by opening a terminal and typing:

python --version

Once Python is ready, install Flask using pip, Python's package manager:

pip install flask

This downloads Flask and its dependencies, including Werkzeug and Jinja2. To verify the installation worked, start a Python shell and import Flask:

python -c "import flask; print(flask.__version__)"

If you see a version number, you're ready to go. Flask is lightweight by design โ€” the entire framework is small enough to read through in a single sitting, which is part of its charm.

Your First Flask Application

Let's build the simplest possible Flask app. Create a file called app.py and add the following code:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, Flask is working!"

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

Now run the application from your terminal:

python app.py

You should see output like Running on http://127.0.0.1:5000. Open that URL in your browser and you'll see "Hello, Flask is working!" Let's break down what happened here:

  • Flask(__name__) creates an instance of the Flask application. The __name__ argument tells Flask where to look for resources like templates and static files.
  • @app.route("/") is a decorator that tells Flask to call the home() function when someone visits the root URL (/).
  • app.run(debug=True) starts the development server with debug mode enabled, which automatically reloads the server when you make changes.

Understanding Routes and View Functions

Routing is how Flask maps URLs to Python functions. Every page on your website is a route, and every route is handled by a view function. You can create as many routes as you need:

@app.route("/about")
def about():
    return "This is the about page"

@app.route("/contact")
def contact():
    return "Get in touch with us"

Routes can also accept dynamic parts. For example, if you want a user profile page where the username changes:

@app.route("/profile/<username>")
def profile(username):
    return f"Profile page for {username}"

The <username> part is a variable that Flask captures and passes to your function. You can restrict the type of variable using converters like int, float, or uuid.

Working with Templates

Returning plain strings works for testing, but real applications need HTML pages. Flask uses Jinja2 templates for this. Create a folder called templates in your project directory, then create a file inside it called home.html:

<!DOCTYPE html>
<html>
<head>
    <title>Flask App</title>
</head>
<body>
    <h1>Welcome, {{ name }}!</h1>
    <p>This page is rendered by Flask and Jinja2.</p>
</body>
</html>

Now update your Python file to render this template:

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("home.html", name="Developer")

The render_template function loads the HTML file and replaces {{ name }} with the value you passed. Jinja2 also supports loops, conditionals, and template inheritance, which let you build complex page layouts without repeating yourself.

Handling Forms and POST Requests

Most web applications need to accept user input. Flask makes this straightforward. Here's a simple contact form example:

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)
messages = []

@app.route("/", methods=["GET", "POST"])
def home():
    if request.method == "POST":
        name = request.form.get("name")
        message = request.form.get("message")
        messages.append({"name": name, "message": message})
        return redirect(url_for("home"))
    return render_template("home.html", messages=messages)

The methods parameter tells Flask which HTTP methods this route accepts. When someone submits the form, Flask captures the form data in request.form. Always use request.form.get() instead of request.form[] to avoid errors when a field is missing.

For security, never trust user input. Always validate and sanitize data before using it. Flask's built-in tools help with this, and libraries like WTForms provide form validation out of the box.

๐Ÿงช Quick Quiz

Who created Flask?