question 470 Secure Python · hard
Build a safe product filter
The admin product search lets staff stack filters like *price < 60* and *category = sports*. Each filter arrives as (column, operator, value) from the browser. Write build_where(filters) that turns them into a SQL WHERE clause and a list of parameters, so that columns and operators come only from allow-lists and every value travels as a parameter.
Function
build_where(filters) → (sql, params)Columns
category, price, rating, stockOperators
=, <, <=, >, >=Resultno filters →
("", []); otherwise " WHERE " followed by "<column> <op> ?" parts joined with " AND ", in the filters' order, and the values in the same orderRaises
ValueError for a column or operator not in its listExample
[("price", "<", 60), ("category", "=", "sports")] → (' WHERE price < ? AND category = ?', [60, 'sports'])