2013-07-25 113 views
5

鉴于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,瓶与它匹配的模式2,指定字符串 '关闭' 的<participant_key> URL参数。我怎样才能使<poll_key>/close路线在<participant_key>路线之前匹配?

+0

尝试在动态之前创建静态路由模式。看起来命令很重要。 – zhangyangyu

回答

4

看到我对于同一个问题的其他答案: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'} 

看起来这是正确的行为。

+0

感谢您的帮助提示。我不知道转换器。对于我问到的简化示例来说,这是一个很好的解决方案,但是我有更多的关键字比'close'更多,我不想匹配'participant_key'url组件。所以如果有效地说“如果不在集合中(匹配,管理,添加等)”会变得相当长。我结束了使用[RegexConverter解决方案](http://stackoverflow.com/questions/5870188/does-flask-support-regular-expressions-in-its-url-routing),并确保我的'participant_key'网址组件某个前缀。 – dmoench

+0

我有点不对,请参阅我的更新。你能为这两条规则获得规则'参数'和'_weights'值吗? – tbicr