Python Flask 和 Psycopg -- WHERE 中的查询字符串 request.get
Python Flask and Psycopg -- Query string request.get in WHERE
将 flask 中的查询字符串变量作为 WHERE 子句中的参数传递给 psycopg 的正确方法是什么?
具体来说,如果没有设置变量,我不想将变量添加到 WHERE 子句中:
id = int(request.args.get('id'))
cur.execute("SELECT * FROM data WHERE id = %s;", id)
如果 id 是 None,我想要没有 WHERE 子句的 SQL:
SELECT * FROM data
唯一的方法是使用 if 语句吗?
如果未提供(有效)id
查询参数,则发出不同的查询:
id = request.args.get('id', type=int)
if id is not None:
cur.execute("SELECT * FROM data WHERE id = %s", (id,))
else:
# No (valid) id given, give everything
cur.execute("SELECT * FROM data")
请注意,我为 MultiDict.get()
method 使用了 type
关键字参数;方法 returns 默认值(None
除非通过 default
参数另外指定)如果键丢失或不能转换为整数。
将 flask 中的查询字符串变量作为 WHERE 子句中的参数传递给 psycopg 的正确方法是什么?
具体来说,如果没有设置变量,我不想将变量添加到 WHERE 子句中:
id = int(request.args.get('id'))
cur.execute("SELECT * FROM data WHERE id = %s;", id)
如果 id 是 None,我想要没有 WHERE 子句的 SQL:
SELECT * FROM data
唯一的方法是使用 if 语句吗?
如果未提供(有效)id
查询参数,则发出不同的查询:
id = request.args.get('id', type=int)
if id is not None:
cur.execute("SELECT * FROM data WHERE id = %s", (id,))
else:
# No (valid) id given, give everything
cur.execute("SELECT * FROM data")
请注意,我为 MultiDict.get()
method 使用了 type
关键字参数;方法 returns 默认值(None
除非通过 default
参数另外指定)如果键丢失或不能转换为整数。