【问题标题】:Eve framework: modify query_stringEve 框架:修改 query_string
【发布时间】:2017-05-08 17:28:44
【问题描述】:

我正在使用 Python EVE 框架编写 API。 在我的on_post_GET 钩子中,出于某种原因,我想用一些附加条件扩展request.query_string

这个request.query_string 看起来像一个原始编码字符串,在现有条件中添加一些新条件是没有用的。

我的字符串看起来像:

embedded=%7B%22some_key%22%3A1%2C%22another_key%22%3A1%2C%22one_more_key%22%3A1%2C%22and_more_key%22%3A1%2C%22and_more%22%3A1%2C%22some_specific_key%22%3A1%2C%22the_last_key%22%3A1%7D&where=%7B%22some_statement%22%3A%22in%28%5B%5C%22value1%5C%22%2C%5C%22value2%5C%22%5D%29%22%7D&max_results=10&page=1&sort=%5B%28%22date%22%2C0%29%5D

所以,我想在WHERE 语句中添加一个附加条件。我可能会以某种方式解析它,但有几件事:

1) 我可能有其他条件,与条件相关的硬编码对我来说看起来很糟糕。 2) 我希望有更好的方法来扩展它。

想法?

【问题讨论】:

  • 你不应该使用pre_GET 钩子来做你想做的事吗?
  • @gcw,这有点棘手,因为我只需要在我的on_fetch 挂钩中为经过身份验证的用户准备一些允许的数据,然后在on_post 挂钩中使用此过滤数据。

标签: python query-string webhooks eve


【解决方案1】:

您应该能够通过在 pre_GET 事件挂钩中处理 lookup 来制作过滤器,如 pyeve 的 documentation 中的此示例:

def pre_GET(resource, request, lookup):
    # only return documents that have a 'username' field.
    lookup["username"] = {'$exists': True}
app = Eve()

app.on_pre_GET += pre_GET
app.run()

【讨论】:

  • 您甚至可以通过在钩子中调用request.args.get('where') 来访问where 的内容,但我认为不可能更改任何内容,因为args dict 的类型是ImmutableDict。请注意,该示例针对的是pre_GET,而不是post_GET,因此您仍然可以将查询的查找过滤器设置为所需的值,而不是处理where 参数。我认为您可以在 where 参数中设置您想要的相同内容。
  • lookup["username"] = {'$exists': True} 这会在 query_string 中转换为 where={"username": $exists}
  • 另外,是否可以使用这种方式lookup["id"] = value 编写带有IN 子句的查询?我的意思是这样的:lookup["id"] = {"$in": [1,2,3]}
  • @smart,是的,像lookup["_id"] = {"$in": ['579a12a23857e47039afedc', '57a3ec63a9ef130011649237']} 这样的东西会起作用。请注意,ID 的默认字段是_id。关于lookup["username"] = {'$exists': True},与where={"username": {"$exists": true}}相同
  • 我知道_id,但我已经监控了我的资源,目前它还没有_id 字段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多