Kahibaro
Discord Login Register

Introduction to Flask

What Is Flask?

Flask is a lightweight web framework for Python. A web framework is a set of tools that makes it easier to build websites and web applications without handling every low-level detail yourself.

Flask is often called a “micro-framework” because:

Flask is great for beginners because:

Typical things you can do with Flask:

Installing Flask

You install Flask like any other Python library, usually using pip.

It’s best practice to work in a virtual environment, but here the focus is on Flask itself. A minimal way to install:

pip install flask

If you want to be explicit and you’re using python:

python -m pip install flask

To check that Flask is installed correctly, you can run in Python interactive mode:

>>> import flask
>>> flask.__version__
'3.0.0'  # your version may be different

Your First Flask App

A minimal Flask application is surprisingly short. Create a new file called app.py and put this inside:

from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
    return "Hello, Flask!"

Line by line:

Running a Flask Development Server

Flask includes a built-in development server. It’s not meant for production, but it’s perfect while learning.

Using the `flask` command

  1. Make sure app.py is in your current folder.
  2. In your terminal, set the app name (on macOS/Linux):
   export FLASK_APP=app.py
   flask run

On Windows (Command Prompt):

   set FLASK_APP=app.py
   flask run
  1. You should see output like:
   * Serving Flask app 'app.py'
   * Running on http://127.0.0.1:5000
  1. Open a browser and go to http://127.0.0.1:5000/.
    You should see: Hello, Flask!.

Enabling Debug Mode (Auto-Reload)

Debug mode automatically restarts the server when you change the code and can show detailed error pages.

To turn it on:

macOS/Linux:

export FLASK_APP=app.py
export FLASK_ENV=development      # for older Flask, or:
export FLASK_DEBUG=1             # for newer
flask run

Windows (Command Prompt):

set FLASK_APP=app.py
set FLASK_ENV=development
flask run

With debug mode on:

Understanding Routes and View Functions

Flask maps URLs (like /, /about, /hello) to Python functions. Each mapping is called a route.

Basic pattern:

@app.route("/some-path")
def some_name():
    return "Something to show"

Examples of multiple routes:

from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
    return "Home page"
@app.route("/about")
def about():
    return "About this site"
@app.route("/contact")
def contact():
    return "Contact page"

Now:

Dynamic Routes with Variables

Sometimes, you want the URL to contain a variable part, like a username or an item id.

You can define a dynamic route using <variable_name>:

from flask import Flask
app = Flask(__name__)
@app.route("/hello/<name>")
def hello(name):
    return f"Hello, {name}!"

Flask tries to match the <name> part to the function parameter name.

You can also specify a type, for example:

Example:

@app.route("/age/<int:age>")
def show_age(age):
    return f"You are {age} years old."

Now /age/30 works, but /age/thirty will not match this route because thirty is not an integer.

Returning HTML Instead of Plain Text

So far, we’ve returned plain text. Browsers can also display HTML, which is how you build real web pages.

A simple HTML response:

from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
    return """
    <html>
        <head>
            <title>My First Flask Page</title>
        </head>
        <body>
            <h1>Welcome!</h1>
            <p>This is a simple HTML page from Flask.</p>
        </body>
    </html>
    """

This is a quick way to get started, but in practice you’ll usually use templates (separate HTML files). Templates are covered in the “Routing and templates” chapter, so here we just show the inline idea.

Using `request` Data (Basic Idea)

For more interactive pages, the server needs to read information sent by the browser (e.g. form data, query parameters). Flask lets you access this using the request object.

A very simple example using query parameters (the part after ? in a URL):

from flask import Flask, request
app = Flask(__name__)
@app.route("/greet")
def greet():
    name = request.args.get("name", "stranger")
    return f"Hello, {name}!"

Now:

We will go deeper into handling forms and user input in later sections, but this shows how Flask connects URLs, data, and Python code.

Common Folder Structure (Basic Overview)

Even for small apps, it’s useful to know the typical layout of a Flask project. A very common minimal structure is:

your_project/
    app.py
    templates/
    static/

Typical uses:

In this introduction, we’re mostly working with app.py. The “Routing and templates” chapter will show how to use templates/ and static/ in detail.

A Tiny Example App: “Mini Homepage”

Putting it all together, here’s a small app with multiple routes and a dynamic route:

from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def home():
    return """
    <h1>Welcome to My Site</h1>
    <p>Try visiting <a href="/about">/about</a> or <a href="/hello?name=Alex">/hello?name=Alex</a>.</p>
    """
@app.route("/about")
def about():
    return "<h2>About</h2><p>This is a tiny Flask app example.</p>"
@app.route("/hello")
def hello():
    name = request.args.get("name", "friend")
    return f"<h2>Hello, {name}!</h2>"

Steps to run:

  1. Save as app.py.
  2. Install Flask with pip install flask if you haven’t.
  3. Set FLASK_APP=app.py in your terminal.
  4. Run flask run.
  5. Visit:
    • / for the home page
    • /about for the about page
    • /hello?name=YourName to see a personalized greeting.

Summary

In this introduction to Flask, you’ve seen:

Next, you’ll learn how to create more structured pages using templates, handle user input with forms, and build more capable web applications.

Views: 17

Comments

Please login to add a comment.

Don't have an account? Register now!