Skip to main content

Flask Introduction

What is Flask?

Flask logo

Flask is a lightweight, micro web framework written in Python. It's designed to make getting started with web development quick and easy, with the ability to scale up to complex applications. Unlike larger frameworks that might include an ORM (Object-Relational Mapper), form validation, and other components, Flask aims to keep the core simple but extensible.

Created by Armin Ronacher in 2010, Flask has grown to become one of the most popular Python web frameworks due to its simplicity and flexibility. It gives developers the freedom to choose the tools and libraries they want to use, rather than enforcing specific ones.

Why Use Flask?

  • Lightweight: Minimal core with no dependencies other than Python itself and a few libraries
  • Extensible: Easy to add functionality through extensions
  • Flexible: No strict conventions, giving developers freedom
  • Beginner-friendly: Simple to learn and understand
  • Microservices: Great for building small services or APIs
  • Development speed: Get a web application up and running quickly

Prerequisites

Before getting started with Flask, you should have:

  • Basic knowledge of Python
  • Understanding of HTML (for templates)
  • A development environment set up with Python installed
  • Familiarity with command-line interfaces

Installing Flask

To install Flask, we'll use pip, Python's package installer. Open your terminal or command prompt and run:

bash
pip install flask

After installation, we can verify it worked by checking the version:

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

This should print the installed Flask version, like 2.3.3.

Your First Flask Application

Let's create a simple "Hello, World!" application to understand the basics of Flask.

  1. Create a new file called app.py:
python
from flask import Flask

# Create an instance of the Flask class
app = Flask(__name__)

# Define a route and the function to handle it
@app.route('/')
def hello_world():
return 'Hello, World!'

# Run the application if this file is executed directly
if __name__ == '__main__':
app.run(debug=True)
  1. Run the application:
bash
python app.py
  1. Open your web browser and navigate to http://127.0.0.1:5000/. You should see "Hello, World!" displayed.

Understanding the Code

Let's break down what's happening in our simple Flask application:

  1. Import the Flask class: from flask import Flask

    This imports the Flask class from the flask module.

  2. Create a Flask application: app = Flask(__name__)

    This creates an instance of the Flask class. The __name__ parameter is a Python predefined variable representing the name of the current module.

  3. Define a route: @app.route('/')

    This decorator tells Flask what URL should trigger our function. In this case, / represents the root URL.

  4. Define a view function: def hello_world():

    This function returns the content that will be displayed in the browser.

  5. Run the application: app.run(debug=True)

    This starts the development server. The debug=True parameter enables debug mode, which shows detailed error messages and automatically reloads the server when code changes.

Routes and Views

Routes and views are fundamental concepts in Flask:

  • Routes define the URLs that your application will respond to
  • Views are the functions that execute when those URLs are requested

Multiple Routes

Let's add more routes to our application:

python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
return 'Home Page'

@app.route('/about')
def about():
return 'About Page'

@app.route('/contact')
def contact():
return 'Contact Us'

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

Now, you can visit:

  • http://127.0.0.1:5000/ for the home page
  • http://127.0.0.1:5000/about for the about page
  • http://127.0.0.1:5000/contact for the contact page

Dynamic Routes

You can create dynamic routes that accept parameters:

python
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
return 'Home Page'

@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return f'User: {username}'

@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return f'Post: {post_id}'

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

In this example:

  • Visiting http://127.0.0.1:5000/user/john will display "User: john"
  • Visiting http://127.0.0.1:5000/post/42 will display "Post: 42"

The <username> syntax creates a dynamic part in the URL, and the value is passed to the function as a parameter. You can also specify the type using <int:post_id>, which ensures the parameter is an integer.

Request and Response Objects

Flask provides access to request data through the request object, and you can customize responses using the Response object:

python
from flask import Flask, request, redirect, url_for

app = Flask(__name__)

@app.route('/')
def home():
user_agent = request.headers.get('User-Agent')
return f'Your browser is: {user_agent}'

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
return f'Hello, {username}!'
else:
return '''
<form method="post">
<input type="text" name="username">
<input type="submit" value="Log In">
</form>
'''

@app.route('/redirect')
def redirect_example():
return redirect(url_for('home'))

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

This example demonstrates:

  • Reading HTTP headers with request.headers
  • Handling different HTTP methods (GET, POST)
  • Processing form data with request.form
  • Redirecting to other routes with redirect() and url_for()

A Real-world Example: To-Do Application

Let's create a simple to-do list application to tie everything together:

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

app = Flask(__name__)

# Store tasks in a simple list (in a real app, you would use a database)
tasks = []

@app.route('/')
def index():
return render_template('index.html', tasks=tasks)

@app.route('/add', methods=['POST'])
def add():
task = request.form.get('task')
if task:
tasks.append(task)
return redirect(url_for('index'))

@app.route('/delete/<int:task_id>')
def delete(task_id):
if 0 <= task_id < len(tasks):
tasks.pop(task_id)
return redirect(url_for('index'))

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

For this to work, you need to create a templates folder with an index.html file:

html
<!DOCTYPE html>
<html>
<head>
<title>Flask Todo App</title>
<style>
body { font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; }
ul { padding-left: 20px; }
form { margin-bottom: 20px; }
input[type="text"] { padding: 8px; width: 70%; }
button { padding: 8px 16px; background: #4CAF50; color: white; border: none; cursor: pointer; }
.delete { color: red; text-decoration: none; margin-left: 10px; }
</style>
</head>
<body>
<h1>Todo List</h1>

<form action="/add" method="post">
<input type="text" name="task" placeholder="Add a new task" required>
<button type="submit">Add</button>
</form>

<ul>
{% for task in tasks %}
<li>
{{ task }}
<a href="{{ url_for('delete', task_id=loop.index0) }}" class="delete">Delete</a>
</li>
{% endfor %}
</ul>
</body>
</html>

This application allows you to:

  1. Add tasks through a form
  2. Display all tasks in a list
  3. Delete tasks by clicking a delete link

It demonstrates several Flask concepts:

  • Template rendering with render_template
  • Form handling
  • Dynamic route parameters
  • Redirects

Summary

In this introduction to Flask, we've covered:

  • What Flask is and why it's useful
  • Installing Flask and setting up a basic application
  • Creating routes and views
  • Handling dynamic routes with parameters
  • Working with request and response objects
  • Building a simple to-do application as a practical example

Flask's simplicity makes it an excellent choice for beginners, while its flexibility allows it to scale for more complex applications. As you become more comfortable with Flask, you can explore additional features like templates, database integration, user authentication, and more.

Additional Resources

Exercises

  1. Modify the "Hello, World!" application to display your name instead.
  2. Create a Flask application with routes for a homepage, about page, and contact page.
  3. Build a simple calculator application that can add, subtract, multiply, and divide numbers.
  4. Extend the to-do application to allow editing tasks and marking them as complete.
  5. Create a blog application where users can view a list of posts and individual post details.


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)