我正在尝试使 LISTEN channelname
可配置。
queue_listen_name = config["database"]["listen_channel"]
cur.execute("LISTEN %s;", (queue_listen_name,))
这段代码失败了,因为 postgresql 在收听 channel 时不喜欢单引号:
psycopg2.ProgrammingError: syntax error at or near "'channel_name'"
LINE 1: LISTEN 'channel_name';
它在使用双引号时有效(在 psql 上测试)。
我能做什么?由于明显的 SQL 注入(inject)原因,我不想自己构建一个字符串然后对该字符串使用 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
关于python - 听 channel 名称;由于 ' vs. "而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48075442/