【发布时间】:2021-01-06 17:01:39
【问题描述】:
我正在使用 django 框架创建一个 Web 应用程序。在其中一个 SQL 查询中,我必须连接多个表并使用用户输入作为“where”子句的一部分来获取结果。由于查询相当复杂,我选择使用原始 SQL 而不是 django 框架。
查询的简化形式是:
select * from table where {where_clause}
where_clause 将是 col1>100 and col2>50 and col3 <40 的形式,依此类推
这部分是根据用户输入在前端创建的(有点像股票筛选器)。
为了使查询免受 SQL 注入的影响,我决定使用 psycopg2 将查询构建为:
query = sql.SQL("select {field} from {table} where {pkey} = %s").format(
field=sql.Identifier('my_name'),
table=sql.Identifier('some_table'),
pkey=sql.Identifier('id'))
即使我将where_clause 的所有部分分成标识符和字面量,我也不知道所有列都事先用这种方式写什么。用户可能会选择许多列进行过滤。
如何确保查询安全?
【问题讨论】:
标签: python sql django security sql-injection