如果仅用于原始SQL查询,SQLAlchemy仍然建议使用吗?

Cyr*_* N. 13 python orm sqlalchemy flask

使用Flask,我很想知道SQLAlchemy是否仍然是使用原始SQL(直接SELECT x FROM table WHERE ...)而不是使用ORM 查询数据库的最佳方式,或者是否有更简单但更强大的替代方案?

谢谢你的回复.

Mar*_*ers 17

我一直使用SQLAlchemy进行直接查询.

主要优点:它为您提供针对SQL注入攻击的最佳保护.SQLAlchemy做了正确的事情,无论你抛出什么参数.

我发现它也可以根据条件调整生成的SQL.显示上面有多个过滤器控件的结果集?只需在一组if/elif/else结构中构建您的查询,您就知道您的SQL仍然是金色的.

以下是一些实时代码的摘录(较旧的SA版本,因此语法可能略有不同):

# Pull start and end dates from form
# ...
# Build a constraint if `start` and / or `end` have been set.
created = None
if start and end:
    created = sa.sql.between(msg.c.create_time_stamp, 
        start.replace(hour=0, minute=0, second=0),
        end.replace(hour=23, minute=59, second=59))
elif start:
    created = (msg.c.create_time_stamp >= 
               start.replace(hour=0, minute=0, second=0))
elif end:
    created = (msg.c.create_time_stamp <= 
               end.replace(hour=23, minute=59, second=59))

# More complex `from_` object built here, elided for example
# [...]
# Final query build
query = sa.select([unit.c.eli_uid], from_obj=[from_])
query = query.column(count(msg.c.id).label('sent'))
query = query.where(current_store)
if created:
    query = query.where(created)
Run Code Online (Sandbox Code Playgroud)

这来自的代码要复杂得多,但我想在这里突出显示日期范围代码.如果我必须使用字符串格式化构建SQL,我可能已经在某处引入了SQL注入漏洞,因为它更容易忘记引用值.