Flask Tutorial: Build a Todo App with SQLite

When it comes to building lightweight web applications, REST APIs, or microservices in Python, Flask is one of the most popular and flexible frameworks. Unlike opinionated full-stack frameworks like Django, Flask follows a minimalist 'micro-framework' design, giving developers complete architectural freedom over database selection, template engines, and extension libraries.

This comprehensive tutorial walks through building a complete, production-ready Todo Web Application from scratch using Flask, Jinja2 templates, and an embedded SQLite database.

1. Environment Setup and Dependencies

First, create a dedicated project directory, set up a virtual environment, and install Flask along with Flask-SQLAlchemy for database ORM mapping.

C
# Terminal setup commands
mkdir flask-todo-app
cd flask-todo-app
python -m venv venv
source venv/bin/activate  # On Windows use: venv\Scripts\activate
pip install flask flask-sqlalchemy

2. Configuring Flask App and SQLite Database

Create an app.py file to configure your Flask application instance, define the SQLite database schema model, and initialize the database tables.

C
# app.py
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todo.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# Define Todo Database Model
class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    complete = db.Column(db.Boolean, default=False)

    def __repr__(self):
        return f'<Task {self.id}>'

# Ensure database tables are created within application context
with app.app_context():
    db.create_all()

3. Implementing CRUD Routes

Next, implement the core CRUD routes for listing tasks, creating new entries, updating completion statuses, and deleting tasks.

C
@app.route('/')
def index():
    todo_list = Todo.query.all()
    return render_template('index.html', todo_list=todo_list)

@app.route('/add', methods=['POST'])
def add():
    title = request.form.get('title')
    if title:
        new_todo = Todo(title=title, complete=False)
        db.session.add(new_todo)
        db.session.commit()
    return redirect(url_for('index'))

@app.route('/update/<int:todo_id>')
def update(todo_id):
    todo = Todo.query.get_or_404(todo_id)
    todo.complete = not todo.complete
    db.session.commit()
    return redirect(url_for('index'))

@app.route('/delete/<int:todo_id>')
def delete(todo_id):
    todo = Todo.query.get_or_404(todo_id)
    db.session.delete(todo)
    db.session.commit()
    return redirect(url_for('index'))

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

4. Building the Frontend UI Template

Create a templates directory and add an index.html file using Jinja2 syntax to render tasks dynamically.

C
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask Todo App</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css">
</head>
<body class="bg-gray-100 p-10">
    <div class="max-w-md mx-auto bg-white p-6 rounded-lg shadow">
        <h1 class="text-2xl font-bold mb-4 text-center">My Todo App</h1>
        <form action="/add" method="POST" class="flex mb-4">
            <input type="text" name="title" placeholder="Enter new task..." class="flex-grow border p-2 rounded-l">
            <button type="submit" class="bg-blue-500 text-white px-4 rounded-r">Add</button>
        </form>
        <ul>
            {% for todo in todo_list %}
            <li class="flex justify-between items-center border-b py-2">
                <span class="{% if todo.complete %}line-through text-gray-400{% endif %}">{{ todo.title }}</span>
                <div>
                    <a href="/update/{{ todo.id }}" class="text-sm bg-green-500 text-white px-2 py-1 rounded">{% if todo.complete %}Undo{% else %}Complete{% endif %}</a>
                    <a href="/delete/{{ todo.id }}" class="text-sm bg-red-500 text-white px-2 py-1 rounded ml-2">Delete</a>
                </div>
            </li>
            {% endfor %}
        </ul>
    </div>
</body>
</html>

Conclusion

By combining Flask's lightweight routing capabilities with SQLAlchemy and SQLite, developers can rapidly prototype and deploy robust, database-backed web applications in Python.