Python 设置 SQL 仅当包含在 GET 请求中时查询参数

Python setting SQL query parameters only if included in GET request

我有一个 AWS lambda python 函数,它使用 psycopg2 访问 PostgreSQL 数据库。有很多可选的查询字符串参数,所以我永远不知道查询的确切结构。

我想做的是检查特定参数是否存在。如果是这样,我会为要在我的查询中使用的参数设置一个变量。如果参数未包含在查询字符串中,我想将我的变量设置为其他值。

这是我目前正在尝试 运行 的内容:

location = event['queryStringParameters']['location'] or '*'

    postgres_get_query = "SELECT * FROM table WHERE  location = %(location)s"
    cursor.execute(postgres_get_query, {'location': location})

当我在不传递位置查询字符串参数的情况下尝试 运行 时,我得到 KeyError: 'location'。我理解这个错误是因为 event['queryStringParameters']['location'] 不存在。当该特定语句为假时,我希望发生什么,变量断言应该移动到类似于 javascript 函数的 or 语句。

Python 和 SQL 都不是 Javascript...您必须有条件地构建查询。

location = event['queryStringParameters'].get('location')
postgres_get_query = "SELECT * FROM table "
if location:
    postgres_get_query += " WHERE  location = %(location)s"

如果您有多个可能的条件,您将需要使用 criterias.append("location = %(location)s") 之类的东西,然后在跟踪 WHERE 的同时使用 " AND ".join(criterias)。对空格要大方,SQL 不介意,除非缺少空格。

我能够通过首先将位置变量的默认值设置为 None 然后在传入特定查询字符串时更新它来解决这个问题。

location = None
if event['queryStringParameters'].get('location'):
        location = event['queryStringParameters'].get('location')

接下来我的查询只需要更新以忽略 location 保持为空的情况。

postgres_get_query = "SELECT * FROM table WHERE (location = %(location)s OR %(location)s IS NULL)"

这是做什么的returns所有记录