Fall 2026
  • Discord
  • Gradescope
  • Syllabus

On this page

  • Tracing Requests
  • Debugging
  • SQL Injection
  • Parameter Binding
  • HTML Escaping
  • Regression Tests

Last Day

When a website behaves unexpectedly, the problem might be in the browser, the server, or the database. We’ll follow a request through all three and see how to check that the app handles a visitor’s input safely.

Tracing Requests

A browser sends a request to a server. The server uses its path and method to choose a route, then runs the Python function for that route. The function can read rows from the database and give them to a template. The resulting HTML is what the browser displays.

The values change form along the way. A form field arrives as text; a database query returns rows; a template turns those rows into HTML. We can inspect each form separately to understand how the displayed page was produced.

Consider a community recipe notebook with a page for searching recipe titles. A visitor submits California burrito to the search form. The server reads that text, queries the recipes table, and gives the matching rows to its template.

We can examine the database part without running a web server. Each short Python example below includes its own setup and can run in a separate file. The complete example runs the experiments together. Start by creating a small database in memory:

import sqlite3

con = sqlite3.connect(':memory:')
con.execute('CREATE TABLE recipes (id INTEGER PRIMARY KEY, title TEXT, note TEXT)')
con.execute("""
    INSERT INTO recipes VALUES
        (1, 'California burrito', 'Carne asada & fries'),
        (2, 'Breakfast burrito', 'Add eggs & cheese')
""")
con.commit()

rows = con.execute('SELECT id, title FROM recipes ORDER BY id').fetchall()
print(rows)  # [(1, 'California burrito'), (2, 'Breakfast burrito')]

Each row is a tuple, and the order of its values follows the columns in SELECT. A template could loop over rows and display each row’s title using row[1].

Debugging

Debugging means finding and correcting the cause of unexpected behavior. Start with an input that reproduces the problem, then compare the actual values with what you expected at each step. If the database returns the right rows but the page shows the wrong text, investigate the template. If the query returns no rows, check the query and the saved data first.

A cursor remembers which rows have already been read. fetchone() returns the next row, or None if none remain. fetchall() returns all the remaining rows. To print a result while debugging and still use it afterward, save it in a variable.

This debugging print accidentally takes the rows that the next line needs:

import sqlite3

con = sqlite3.connect(':memory:')
con.execute('CREATE TABLE recipes (id INTEGER PRIMARY KEY, title TEXT, note TEXT)')
con.execute("INSERT INTO recipes VALUES (1, 'California burrito', 'Carne asada & fries'), (2, 'Breakfast burrito', 'Add eggs & cheese')")
con.commit()

cur = con.execute('SELECT title FROM recipes ORDER BY id')
print(cur.fetchall())  # [('California burrito',), ('Breakfast burrito',)]
rows = cur.fetchall()
print(rows)  # []

Fetch once and reuse the list:

import sqlite3

con = sqlite3.connect(':memory:')
con.execute('CREATE TABLE recipes (id INTEGER PRIMARY KEY, title TEXT, note TEXT)')
con.execute("INSERT INTO recipes VALUES (1, 'California burrito', 'Carne asada & fries'), (2, 'Breakfast burrito', 'Add eggs & cheese')")
con.commit()

rows = con.execute('SELECT title FROM recipes ORDER BY id').fetchall()
print(rows)
titles = [row[0] for row in rows]

A change visible through one connection might not have been saved. With the sqlite3.connect(...) setup we use, INSERT, UPDATE, and DELETE start a transaction: a group of changes waiting to be saved together. commit() saves them. rollback() discards changes since the last commit, and closing the connection without committing also discards pending changes. A query through that same connection can see its pending changes, so checking only that query can miss a persistence bug.

This example uses a file so we can close it and open it again. Run it in an empty directory:

import sqlite3

db = sqlite3.connect('recipe_notes.db')
db.execute('CREATE TABLE notes (text TEXT)')
db.execute("INSERT INTO notes VALUES ('Add salsa')")
db.commit()
db.execute("UPDATE notes SET text = 'Add guacamole'")
print(db.execute('SELECT text FROM notes').fetchone()[0])  # Add guacamole
db.close()

db = sqlite3.connect('recipe_notes.db')
print(db.execute('SELECT text FROM notes').fetchone()[0])  # Add salsa
db.close()

The update needs its own commit() before the first connection closes.

SQL Injection

A database treats an SQL statement as instructions. If we build that statement by inserting a visitor’s text directly into it, the visitor can change those instructions. That is SQL injection. An ordinary apostrophe can break the query; deliberately chosen input can change which rows it reads or modifies.

To understand an injection, first write out the complete SQL string. Track where each quoted string ends, then read the resulting conditions. SQL’s AND joins conditions more tightly than OR; parentheses can change that grouping. The sequence -- starts a comment that continues to the end of the line.

Here is an unsafe title search in our local recipe database:

import sqlite3

con = sqlite3.connect(':memory:')
con.execute('CREATE TABLE recipes (id INTEGER PRIMARY KEY, title TEXT, note TEXT)')
con.execute("INSERT INTO recipes VALUES (1, 'California burrito', 'Carne asada & fries'), (2, 'Breakfast burrito', 'Add eggs & cheese')")
con.commit()

title = "California burrito' OR title='Breakfast burrito"
sql = "SELECT title FROM recipes WHERE title='" + title + "' ORDER BY id"
print(sql)
# SELECT title FROM recipes WHERE title='California burrito' OR title='Breakfast burrito' ORDER BY id
print(con.execute(sql).fetchall())  # [('California burrito',), ('Breakfast burrito',)]

The first quote in title ends the SQL string containing California burrito. The following OR becomes part of the query’s condition, so both recipes match.

A comment can remove a condition that the application added:

import sqlite3

con = sqlite3.connect(':memory:')
con.execute('CREATE TABLE recipes (id INTEGER PRIMARY KEY, title TEXT, note TEXT)')
con.execute("INSERT INTO recipes VALUES (1, 'California burrito', 'Carne asada & fries'), (2, 'Breakfast burrito', 'Add eggs & cheese')")
con.commit()

title = "California burrito'--"
sql = "SELECT title FROM recipes WHERE title='" + title + "' AND id > 1"
print(sql)
# SELECT title FROM recipes WHERE title='California burrito'--' AND id > 1
print(con.execute(sql).fetchall())  # [('California burrito',)]

The database ignores the AND id > 1 after --.

The same mistake can affect writes. An INSERT may contain several comma-separated value tuples. Input that closes one tuple and starts another can add an extra row if it is pasted into the statement.

Use a separate in-memory table for this experiment:

import sqlite3

db = sqlite3.connect(':memory:')
db.execute('CREATE TABLE suggestions (title TEXT, note TEXT)')
title = "Burrito', 'Try it'), ('Taco"
note = 'Try it'
sql = "INSERT INTO suggestions VALUES ('" + title + "', '" + note + "')"
print(sql)
# INSERT INTO suggestions VALUES ('Burrito', 'Try it'), ('Taco', 'Try it')
db.execute(sql)
print(db.execute('SELECT count(*) FROM suggestions').fetchone()[0])  # 2

Parameter Binding

Parameter binding passes values to the database separately from the SQL statement. We write the statement with ? placeholders, then supply a sequence containing one value for each placeholder, in order. The database can use those values without interpreting their contents as SQL syntax. This also lets us store ordinary text containing apostrophes.

A one-element tuple needs a comma: (title,). For several values, use (title, note). A list works too. Placeholders stand for values; keep column names and SQL keywords in the statement itself.

Repair the recipe search by separating the title from the statement:

import sqlite3

con = sqlite3.connect(':memory:')
con.execute('CREATE TABLE recipes (id INTEGER PRIMARY KEY, title TEXT, note TEXT)')
con.execute("INSERT INTO recipes VALUES (1, 'California burrito', 'Carne asada & fries'), (2, 'Breakfast burrito', 'Add eggs & cheese')")
con.commit()

def find_titles(title):
    rows = con.execute(
        'SELECT title FROM recipes WHERE title = ? ORDER BY id',
        (title,),
    ).fetchall()
    return [row[0] for row in rows]

print(find_titles('California burrito'))  # ['California burrito']
print(find_titles("California burrito' OR title='Breakfast burrito"))  # []

The second call searches for the entire supplied title, including its quotes and OR. There is no recipe with that title.

Binding also works for writes:

import sqlite3

con = sqlite3.connect(':memory:')
con.execute('CREATE TABLE recipes (id INTEGER PRIMARY KEY, title TEXT, note TEXT)')
con.execute("INSERT INTO recipes VALUES (1, 'California burrito', 'Carne asada & fries'), (2, 'Breakfast burrito', 'Add eggs & cheese')")
con.commit()

title = "Chef's burrito"
note = 'Toast the tortilla'
con.execute('INSERT INTO recipes (title, note) VALUES (?, ?)', (title, note))
con.commit()
print(con.execute('SELECT title FROM recipes WHERE title = ?', (title,)).fetchall())  # [("Chef's burrito",)]

Parameter binding preserves SQL’s intended operations. A bound value used with LIKE still follows LIKE’s rules: % matches any sequence of characters and _ matches one character. Use = when you want an exact value.

Both queries bind the same value, but ask different questions:

import sqlite3

con = sqlite3.connect(':memory:')
con.execute('CREATE TABLE recipes (id INTEGER PRIMARY KEY, title TEXT, note TEXT)')
con.execute("INSERT INTO recipes VALUES (1, 'California burrito', 'Carne asada & fries'), (2, 'Breakfast burrito', 'Add eggs & cheese')")
con.commit()

pattern = 'B%'
print(con.execute('SELECT title FROM recipes WHERE title LIKE ?', (pattern,)).fetchall())
# [('Breakfast burrito',)]
print(con.execute('SELECT title FROM recipes WHERE title = ?', (pattern,)).fetchall())
# []

HTML Escaping

The browser is another program that interprets text as instructions. If a visitor’s note is pasted into HTML, angle brackets in the note may become tags. HTML escaping represents special characters so that the browser displays them as text instead of treating them as markup. For example, &lt; represents <, &gt; represents >, and &amp; represents &.

Python’s html.escape returns an escaped copy of a string; it does not change the original. The HTML templates configured in the backend reading escape inserted values automatically. The examples here use escape directly so we can see the resulting HTML.

A recipe note should not make its own HTML elements:

from html import escape

note = '<b>More salsa</b> & more guacamole'
page = '<p>' + escape(note) + '</p>'
print(page)  # <p>&lt;b&gt;More salsa&lt;/b&gt; &amp; more guacamole</p>
print(note)  # <b>More salsa</b> & more guacamole

The outer <p> is part of our page. The escaped <b> belongs to the visitor’s text and will appear literally in the browser. Escape the note when inserting it into HTML; escaping the entire page would also turn our <p> into displayed text.

Binding a value for SQL does not escape it for HTML. A note can be stored safely in the database and still become unwanted markup when displayed. Keep the original text in storage and escape it when producing HTML.

This note is stored unchanged, then escaped for display:

import sqlite3

con = sqlite3.connect(':memory:')
con.execute('CREATE TABLE recipes (id INTEGER PRIMARY KEY, title TEXT, note TEXT)')
con.execute("INSERT INTO recipes VALUES (1, 'California burrito', 'Carne asada & fries'), (2, 'Breakfast burrito', 'Add eggs & cheese')")
con.commit()
from html import escape

con.execute('UPDATE recipes SET note = ? WHERE id = ?', ('Fries & <salsa>', 1))
con.commit()
stored = con.execute('SELECT note FROM recipes WHERE id = 1').fetchone()[0]
print(stored)  # Fries & <salsa>
print(escape(stored))  # Tea &amp; &lt;cake&gt;

Regression Tests

A regression test records behavior that should keep working after a change. When fixing a bug, write a test that fails with the original code and passes with the repair. Also check an ordinary successful case: a search that always returns an empty list would reject the injected title but break real searches.

Choose cases that exercise different assumptions. For this recipe search, those include an existing title, a missing title, an apostrophe in a real title, and text containing SQL syntax. For saved data, close and reopen the database before checking it. For displayed text, inspect the generated HTML as well as the value in storage.

This complete test script creates a database, defines the search function, and checks several inputs:

import sqlite3

con = sqlite3.connect(':memory:')
con.execute('CREATE TABLE recipes (id INTEGER PRIMARY KEY, title TEXT, note TEXT)')
con.execute("INSERT INTO recipes VALUES (1, 'California burrito', 'Carne asada & fries'), (2, 'Breakfast burrito', 'Add eggs & cheese')")
con.commit()

def find_titles(title):
    rows = con.execute(
        'SELECT title FROM recipes WHERE title = ? ORDER BY id',
        (title,),
    ).fetchall()
    return [row[0] for row in rows]

con.execute('INSERT INTO recipes (title, note) VALUES (?, ?)', ("Chef's burrito", 'Toast the tortilla'))
con.commit()

assert find_titles('California burrito') == ['California burrito']
assert find_titles('Quesadilla') == []
assert find_titles("Chef's burrito") == ["Chef's burrito"]
assert find_titles("California burrito' OR title='Breakfast burrito") == []

To check that the last test catches the original bug, temporarily replace the bound query with the unsafe concatenated query from the SQL Injection section. That test should fail because the unsafe version returns two titles. Restore the bound query afterward.

The programs you have built this term combine text processing, data storage, automation, and web interfaces. Tests give us evidence about particular inputs; later computer science courses also study how to prove properties of programs and measure the time and memory they need. Data structures and algorithms, systems, and security each give us more ways to understand why a program works or why it fails.