KAHIBARO Bookshelves
Discord Login Register

15.2. 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:

  • It gives you the basics: handling web requests and sending responses.
  • It doesn’t force you to use a specific database or structure.
  • You can add extra features (like forms, authentication, databases) using extensions when you need them.

Flask is great for beginners because:

  • It’s simple to get started.
  • A basic app can be only a few lines of code.
  • You see results in your browser quickly.

Typical things you can do with Flask:

  • Serve web pages (HTML).
  • Create APIs that send and receive data (JSON).
  • Build small web tools, dashboards, or prototypes.

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:

  • from flask import Flask
    Imports the main Flask class from the flask package.
  • app = Flask(__name__)
    Creates a Flask application object. __name__ tells Flask where your app is defined (used for locating templates, static files, etc.).
  • @app.route("/")
    This is a route decorator. It tells Flask: “When someone visits the / URL (the home page), call the function below.”
  • def home():
    Defines a view function that runs when a user visits /.
  • return "Hello, Flask!"
    Whatever this function returns is sent as the HTTP response to the browser. Here, it’s just plain text.

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:

  • When you edit and save app.py, Flask will reload automatically.
  • If there’s an error, you see a helpful debug page in the browser.

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:

  • http://127.0.0.1:5000/ → shows “Home page”
  • http://127.0.0.1:5000/about → shows “About this site”
  • http://127.0.0.1:5000/contact → shows “Contact page”

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}!"
  • Visiting /hello/Alex → “Hello, Alex!”
  • Visiting /hello/Sam → “Hello, Sam!”

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

You can also specify a type, for example:

  • <int:age> for integers
  • <float:score> for floating-point numbers

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:

  • /greet → “Hello, stranger!”
  • /greet?name=Alex → “Hello, Alex!”

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:

  • app.py – main Flask application file.
  • templates/ – HTML templates (used with Flask’s templating system).
  • static/ – static files like CSS, JavaScript, and images.

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:

  • What Flask is and why it’s useful for web development with Python.
  • How to install Flask using pip.
  • How to write and run a minimal Flask app with app.py.
  • How routes map URLs to Python functions.
  • How to define static and dynamic routes (with variables).
  • How to return plain text and simple HTML.
  • A glimpse of using request to read data from the URL.

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

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms