Answers:
即使Armin用可接受的答案击败了我,我仍然认为我会显示一个简短的示例,说明如何在Flask中实现正则表达式匹配器,以防万一有人想要如何完成此工作的示例。
from flask import Flask
from werkzeug.routing import BaseConverter
app = Flask(__name__)
class RegexConverter(BaseConverter):
def __init__(self, url_map, *items):
super(RegexConverter, self).__init__(url_map)
self.regex = items[0]
app.url_map.converters['regex'] = RegexConverter
@app.route('/<regex("[abcABC0-9]{4,6}"):uid>-<slug>/')
def example(uid, slug):
return "uid: %s, slug: %s" % (uid, slug)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
该URL应返回200:http:// localhost:5000 / abc0-foo /
该网址应返回404:http:// localhost:5000 / abcd-foo /
self.regex
,但是匹配在哪里发生?
from random import randrange
from werkzeug.routing import Rule, Map, BaseConverter, ValidationError
class BooleanConverter(BaseConverter):
def __init__(self, url_map, randomify=False):
super(BooleanConverter, self).__init__(url_map)
self.randomify = randomify
self.regex = '(?:yes|no|maybe)'
def to_python(self, value):
if value == 'maybe':
if self.randomify:
return not randrange(2)
raise ValidationError()
return value == 'yes'
def to_url(self, value):
return value and 'yes' or 'no'
url_map = Map([
Rule('/vote/<bool:werkzeug_rocks>', endpoint='vote'),
Rule('/vote/<bool(randomify=True):foo>', endpoint='foo')
], converters={'bool': BooleanConverter})
to_python
呢
您还可以编写一条捕获所有类型的路由并在该方法内执行复杂的路由:
from flask import Flask
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'], defaults={'path': ''})
@app.route('/<path:path>', methods=['GET', 'POST'])
def catch_all(path):
return 'You want path: %s' % path
if __name__ == '__main__':
app.run()
这将匹配任何请求。在此处查看更多详细信息:捕获所有URL。