小能豆

如何指定多个“where”或“order_by”条件?

py

找到有关这方面的信息并不是一件容易的事,所以想知道是否有一些我可以查看的文档,但基本上我想实现将多个条件传递给要么.where()或者.order_by()要么避免 SQL 注入。

我现在的做法如下:两个表:存档和备份,我尝试按archive.cityarchive.zip和进行筛选backup.serial,然后按所有这些字段进行排序。这些值来自用户通过 URL 参数提供的值,因此我需要确保这些值不会受到 SQL 注入攻击并且经过了清理。

filters = []
sorts = []

    if 'city' in query:
            city = query['city']
            filters.append(text(f'archive.city = {city}')) 
            sorts.append(text(f'archive.city = {city}')) 

    if 'zip' in query:
            zip = query['zip']
            filters.append(text(f'archive.zip > {zip}'))    
            sorts.append(text(f'archive.zip DESC'))  

    if 'serial' in query:
            serial = query['serial']
            filters.append(text(f'backup.serial IN {serial}'))    
            sorts.append(text(f'backup.serial ASC')) 

    with Session(engine) as session:
        results = session.exec(select(Archive, Backup)
                               .join(Backup)
                               .where(and_(*filters))
                               .order_by(*sorts).all()

据我所知,这text()并不安全,不易受到 SQL 注入的侵害,那么我该如何转换它,使它能够按照我想要的方式运行,并且不易受到 SQL 注入的侵害?


阅读 6

收藏
2024-11-04

共1个答案

小能豆

您可以多次调用和.where(),SQLAlchemy 将按逻辑为您“与”它们:.order_by()``select()

qry = select(Task)
qry = qry.where(Task.description == "foo")
qry = qry.where(Task.priority < 2)
qry = qry.order_by(Task.priority)
qry = qry.order_by(Task.description)

print(qry)
"""
SELECT task.id, task.description, task.priority 
FROM task 
WHERE task.description = :description_1 AND task.priority < :priority_1 
ORDER BY task.priority, task.description
"""
2024-11-04