8

鉴于Flask Routes 不是从上到下的模式匹配,如何处理以下问题?

我有以下路线:

  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>

4

1 回答 1

6

请参阅我对同一问题的其他答案: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. 对于/<poll_key>/close(True, -2, [(1, 100), (0, -5)])
  3. 对于/<poll_key>/<participant_key>(True, -2, [(1, 100), (1, 100)])

这意味着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'}

看起来这是正确的行为。

于 2013-07-26T11:38:13.450 回答