烧瓶路线模式匹配顺序

时间:2013-07-25 21:18:57

标签: python pattern-matching flask

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

我有以下路线:

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

1 个答案:

答案 0 :(得分:5)

请参阅我对同一问题的其他答案: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. for /<poll_key>/close(True, -2, [(1, 100), (0, -5)])
  3. for /<poll_key>/<participant_key>(True, -2, [(1, 100), (1, 100)])
  4. 这意味着static的优先级高于其他close<participant_key>的优先级高于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'}
    

    输出:

    {{1}}

    看起来这是正确的行为。

相关问题