【问题标题】:Flask Route Pattern Matching OrderFlask 路由模式匹配顺序
【发布时间】:2013-07-25 23:44:39
【问题描述】:

鉴于Flask Routes are not pattern matched from top to bottom,如何处理以下问题?

我有以下路线:

  1. /<poll_key>/close
  2. /<poll_key>/<participant_key>

如果我向http://localhost:5000/example-poll-key/close 发出请求,Flask 会将其匹配为模式 2,将字符串“close”分配给<participant_key> URL 参数。如何使<poll_key>/close 路由在<participant_key> 路由之前匹配?

【问题讨论】:

  • 尝试在动态路由模式之前创建静态路由模式。看来顺序很重要。

标签: python pattern-matching flask


【解决方案1】:

查看我对同一问题的其他回答:https://stackoverflow.com/a/17146563/880326

看起来最好的解决方案是添加您自己的转换器并创建路由

/<poll_key>/close
/<poll_key>/<no(close):participant_key>

no 转换器的定义位置

class NoConverter(BaseConverter):

    def __init__(self, map, *items):
        BaseConverter.__init__(self, map)
        self.items = items

    def to_python(self, value):
        if value in self.items:
            raise ValidationError()
        return value

更新:

我错过了match_compare_key

  1. 对于static 端点:(True, -2, [(0, -6), (1, 200)])
  2. 对于/&lt;poll_key&gt;/close(True, -2, [(1, 100), (0, -5)])
  3. 对于/&lt;poll_key&gt;/&lt;participant_key&gt;(True, -2, [(1, 100), (1, 100)])

这意味着static 的优先级高于其他close 的优先级高于&lt;participant_key&gt;

例子:

from flask import Flask

app = Flask(__name__)
app.add_url_rule('/<poll_key>/close', 'close',
                 lambda **kwargs: 'close\t' + str(kwargs))
app.add_url_rule('/<poll_key>/<participant_key>', 'p_key',
                 lambda **kwargs: 'p_key\t' + str(kwargs))


client = app.test_client()

print client.get('/example-poll-key/close').data
print client.get('/example-poll-key/example-participant-key').data

这个输出:

close   {'poll_key': u'example-poll-key'}
p_key   {'participant_key': u'example-participant-key', 'poll_key': u'example-poll-key'}

看起来这是正确的行为。

【讨论】:

  • 感谢您的有用提示。我不知道转换器。对于我询问的简化示例,这是一个很好的解决方案,但是我有比“关闭”更多的关键字,我不想匹配participant_key url 组件。因此,有效地说“如果不在集合中匹配(关闭、管理、添加等)”会变得很长。我最终使用了这个RegexConverter solution,并确保我的participant_key url 组件有一个特定的前缀。
  • 我错了,请看我的更新。你能得到这两条规则的arguments_weights 值吗?
猜你喜欢
  • 2015-04-25
  • 2018-12-08
  • 2017-05-06
  • 1970-01-01
  • 2018-10-04
  • 1970-01-01
  • 2019-07-29
  • 2023-03-17
  • 2012-06-17
相关资源
最近更新 更多