听channel_name;由于 ' 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)

从手册中获取,两者都应该工作,并被描述为"安全":

# 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

最新更新