如何在 python 中获取经过清理的 postgres SQL 字符串供以后使用?

How to get sanitized postgres SQL string in python for later use?

我有一个查询要附加到稍后将执行的文件(以生成查询列表)。

location_filter="SELECT id FROM developers WHERE location='%s'"
out_file.write((location_filter, (location)))

但是写入的输出无法在 pgadmin 中执行:

("SELECT id FROM developers WHERE location='%s'", u'Seattle')

如何安全地生成此语句?

conn = psycopg2.connect(database='cpn')
cur = conn.cursor()

location_filter = "SELECT id FROM developers WHERE location = %s"
out_file.write(cur.mogrify(location_filter, (location,)))