python - 听 channel 名称;由于 ' vs. "而失败

标签 python python-3.x postgresql psycopg2

我正在尝试使 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/

相关文章:

python - 在 django 的模板上为我们获取当前使用的 url 面包屑?

python - 在 Python 队列中伪造一个插入

python - 插入文本后文本小部件何时更新

Postgresql 和 SSL 证书

postgresql - 在创建用户所有评论的表时,使用 SERIAL 作为主键是否合适?

python - 使用 Python 通过 Selenium WebDriver 打开 chrome 扩展

python - 使用 Python 在 Lambda 中自定义日志文件

python - 嵌套 JSON 和 Pandas 规范化

python - List vs Dictionary vs Set用于查找数字出现的次数

python - postgres 中的条件行计数器