SQLAlchemy 如何转义 text() 中的绑定参数?

SQLAlchemy how to escape a bind parameter inside of text()?

如何在传递给 text() 的字符串中转义 : 以防止 SQLAlchemy 将其视为绑定参数?

conn.execute(text("select 'My favorite emoticon is :p' from dual")).fetchone()

将导致:

sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter 'p'
(Background on this error at: http://sqlalche.me/e/14/cd3x)

'

这有点令人困惑,因为从数据库中选择字符串的上下文来看 select 'foo :bar baz' 绑定参数在这里没有多大意义。

看起来我可以使用 \ 来避免这种情况,但它说它已被弃用:

>>> conn.execute(text("select 'My favorite emoticon is \:p' from dual")).fetchone()
<stdin>:1: DeprecationWarning: invalid escape sequence \:
('My favorite emoticon is :p',)

docs所述:

For SQL statements where a colon is required verbatim, as within an inline string, use a backslash to escape

但请记住,反斜杠也是 Python 字符串文字中的转义字符,因此

text("select 'My favorite emoticon is \:p' from dual")

不正确,因为 Python 会将 \: 解释为转义字符。我们需要使用“原始字符串”(r"")

text(r"select 'My favorite emoticon is \:p' from dual")

或者转义反斜杠本身

text("select 'My favorite emoticon is \:p' from dual")