Practice ยท 1 of 2
Parameterization beats escaping
Implement two functions that contrast safe and unsafe query building:
- build_query(template, params) โ the parameterized world. The template may contain ? placeholders; values are rendered with repr() (a quote in a value stays a literal quote inside a quoted token, never changing statement structure). Placeholder-count mismatch raises UnsafeQuery('placeholder count mismatch'). Returns (rendered, 'parameterized').
- vulnerable_query(template, values) โ the string-formatting world. Render with template.format(*values); if the result contains drop table (case-insensitive), ' or '1'='1, or a ;, raise UnsafeQuery('injection detected in string-built query'); otherwise return it.
- define class UnsafeQuery(Exception).
The discriminating scenario: O'Brien as a customer name must flow safely through build_query unchanged (quotes preserved) โ while the same string in the vulnerable path is a hand-escaping hazard.
Difficulty: advanced
Back to lesson: Practice: Injection Drills