Skip to content
Language guides Reviewed 2026-09-12

Python secure coding

Python services often pass request data through compact helper functions. The shortness of the code can hide where data becomes an executable instruction. This guide uses Python 3 and the standard sqlite3 module, a convenient local example for Flask or Django teams reviewing database access.

Keep values separate from SQL

Assume db is an open sqlite3.Connection and name is a request-derived string. The table contains fictional customer records.

Unsafe: format the input into the query.

rows = db.execute(
    f"SELECT id FROM customers WHERE name = '{name}'"
).fetchall()

Safer: pass a parameter tuple.

rows = db.execute(
    "SELECT id FROM customers WHERE name = ?", (name,)
).fetchall()

The trailing comma creates a one-element tuple. The placeholder syntax belongs to sqlite3; other database drivers can use different conventions. Python's sqlite3 documentation explains parameter substitution. Do not replace the placeholder with an f-string before sending the query.

If only values vary, query binding keeps their content separate from SQL syntax. A requested column name or sort direction still needs a fixed allowlist. An ORM does not protect a raw SQL string built before the ORM receives it. Authorization must also constrain which rows the user may retrieve.

Check the fix

Use an in-memory database containing O'Reilly and Demo Customer. Search for each name and assert one expected result; search for an unknown name and assert an empty list. The apostrophe should neither break the query nor change its meaning. Close the disposable database after the test.

Review subprocess calls that enable a shell, HTTP clients that disable certificate verification, template escaping, and code that deserializes untrusted objects. Never load an untrusted pickle as a parsing shortcut. Store credentials outside source and rotate any that have already been exposed.

Continue with SQL injection, command injection, TLS verification and insecure deserialization. OWASP's SQL guidance covers the surrounding controls.

These educational examples span Python review topics. The precise checks available in an Offensive360 scan depend on its installed analyzers and configuration.