听 channel_name;由于 ' vs. ' 失败

LISTEN channel_name; fails due to ' vs. "

我正在尝试使 LISTEN channelname 可配置。

queue_listen_name = config["database"]["listen_channel"]
cur.execute("LISTEN %s;", (queue_listen_name,))

这段代码失败了,因为 postgresql 在收听频道时不喜欢单引号:

psycopg2.ProgrammingError: syntax error at or near "'channel_name'"
LINE 1: LISTEN 'channel_name';

它在使用双引号时有效(在 psql 上测试)。

我能做什么?由于明显的 SQL 注入原因,我不想自己构建一个字符串然后在该字符串上使用 cur.execute()

所以这不是我想要做的:

queue_listen_name = "LISTEN {};".format(config["database"]["listen_channel"])
cur.execute(queue_listen_name)

根据手册,这两个都应该有效,并被描述为 "safe":

# This works, but it is not optimal, could crash
queue_listen_name = config["database"]["listen_channel"]
cur.execute("LISTEN %s;" % ext.quote_ident(queue_listen_name))

或更好

from psycopg2 import sql

cur.execute(
    sql.SQL("LISTEN {};")
        .format(sql.Identifier(queue_listen_name)))

您可以在此处阅读有关格式化的更多信息:http://initd.org/psycopg/docs/sql.html