Understanding Flask + SQLite Code Line by Line


📄 app.py â€” Flask + SQLite App (Basic Version)

import sqlite3
from flask import Flask, request, jsonify, g

app = Flask(__name__)
DATABASE = 'tasks.db'

def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(DATABASE)
        g.db.row_factory = sqlite3.Row
    return g.db

@app.teardown_appcontext
def close_db(exception):
    db = g.pop('db', None)
    if db is not None:
        db.close()

def init_db():
    db = get_db()
    db.execute('''
        CREATE TABLE IF NOT EXISTS tasks (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL
        )
    ''')
    db.commit()

@app.route('/tasks', methods=['GET'])
def get_tasks():
    db = get_db()
    tasks = db.execute('SELECT * FROM tasks').fetchall()
    return jsonify([dict(row) for row in tasks])

@app.route('/tasks', methods=['POST'])
def add_task():
    data = request.get_json()
    db = get_db()
    db.execute('INSERT INTO tasks (title) VALUES (?)', (data['title'],))
    db.commit()
    return jsonify({'message': 'Task added'}), 201

@app.route('/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
    data = request.get_json()
    db = get_db()
    db.execute('UPDATE tasks SET title = ? WHERE id = ?', (data['title'], task_id))
    db.commit()
    return jsonify({'message': 'Task updated'})

@app.route('/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
    db = get_db()
    db.execute('DELETE FROM tasks WHERE id = ?', (task_id,))
    db.commit()
    return jsonify({'message': 'Task deleted'})

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

🧩 Code Explanation (Section-by-Section)


1. Importing Required Modules

import sqlite3
from flask import Flask, request, jsonify, g
  • sqlite3: Python’s built-in library to work with SQLite databases.
  • Flask: The main Flask library.
  • request: To get data sent from the client (like from Postman or a form).
  • jsonify: To send data back in JSON format.
  • g: A special Flask object for storing things during a request (used to hold the database connection).

2. Creating Flask App and Database Name

app = Flask(__name__)
DATABASE = 'tasks.db'
  • We create the app using Flask(__name__)
  • DATABASE is just a string that tells us the file name of our SQLite database

3. Connecting to the Database

def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect(DATABASE)
        g.db.row_factory = sqlite3.Row
    return g.db
  • This function connects to the database if it’s not already connected during the request.
  • g.db stores the connection so we can reuse it.
  • row_factory = sqlite3.Row lets us use dictionary-style access to rows (so we can do row['title']).

4. Closing the Database After Use

@app.teardown_appcontext
def close_db(exception):
    db = g.pop('db', None)
    if db is not None:
        db.close()
  • After the request is done, this function closes the database connection automatically.

5. Creating the Tasks Table (Once)

def init_db():
    db = get_db()
    db.execute('''
        CREATE TABLE IF NOT EXISTS tasks (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL
        )
    ''')
    db.commit()
  • This function runs only once (at startup) to create a table called tasks if it doesn’t already exist.
  • Each task has:
    • id: a unique number (auto-generated)
    • title: the text of the task

6. GET /tasks — View All Tasks

@app.route('/tasks', methods=['GET'])
def get_tasks():
    db = get_db()
    tasks = db.execute('SELECT * FROM tasks').fetchall()
    return jsonify([dict(row) for row in tasks])
  • Selects all rows from the tasks table.
  • Converts them to dictionaries so they can be returned as JSON.

7. POST /tasks — Add a New Task

@app.route('/tasks', methods=['POST'])
def add_task():
    data = request.get_json()
    db = get_db()
    db.execute('INSERT INTO tasks (title) VALUES (?)', (data['title'],))
    db.commit()
    return jsonify({'message': 'Task added'}), 201
  • Gets the new task from the user (in JSON format)
  • Inserts the title into the database
  • Sends a success message

✅ Let’s Now Add Comments to the Remaining APIs (PUT & DELETE)

Here’s the updated version of the PUT and DELETE routes with beginner-friendly comments added in:

# PUT /tasks/<id> — Update a task's title
@app.route('/tasks/<int:task_id>', methods=['PUT'])
def update_task(task_id):
    data = request.get_json()  # Get the new title from the request
    db = get_db()
    db.execute(
        'UPDATE tasks SET title = ? WHERE id = ?',
        (data['title'], task_id)  # Replace the title where the ID matches
    )
    db.commit()  # Save the changes to the database
    return jsonify({'message': 'Task updated'})  # Respond with success message

# DELETE /tasks/<id> — Delete a task
@app.route('/tasks/<int:task_id>', methods=['DELETE'])
def delete_task(task_id):
    db = get_db()
    db.execute('DELETE FROM tasks WHERE id = ?', (task_id,))  # Delete the task with matching ID
    db.commit()  # Save the changes
    return jsonify({'message': 'Task deleted'})  # Respond with success message

🎉 You’re Done!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top