Flask是否在其URL路由中支持正则表达式?

时间:2023-01-08 15:46:11

I understand that Flask has the int, float and path converters, but the application we're developing has more complex patterns in its URLs.

我知道Flask有int、float和path转换器,但是我们正在开发的应用程序在其url中有更复杂的模式。

Is there a way we can use regular expressions, as in Django?

是否有一种方法可以像Django那样使用正则表达式?

3 个解决方案

#1


162  

Even though Armin beat me to the punch with an accepted answer I thought I'd show an abbreviated example of how I implemented a regex matcher in Flask just in case anyone wants a working example of how this could be done.

尽管Armin以一个公认的答案打败了我,但我认为我应该展示一个简化的示例,说明我如何在Flask中实现regex matcher,以防有人希望看到如何实现这个示例。

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)

this URL should return with 200: http://localhost:5000/abc0-foo/

这个URL应该返回200:http://localhost:5000/abc0-foo/。

this URL should will return with 404: http://localhost:5000/abcd-foo/

这个URL应该会返回404:http://localhost:5000/abcd-foo/。

#2


47  

You can hook in custom converters that match for arbitrary expressions: Custom Converter

您可以引入与任意表达式匹配的自定义转换器:自定义转换器

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})

#3


15  

You could also write a catch all type of route and do complex routing within the method:

您还可以编写捕获所有类型的路由,并在该方法中执行复杂的路由:

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()

This will match any request. See more details here: Catch-All URL.

这将匹配任何请求。请参阅这里的详细信息:“一网打尽”URL。

#1


162  

Even though Armin beat me to the punch with an accepted answer I thought I'd show an abbreviated example of how I implemented a regex matcher in Flask just in case anyone wants a working example of how this could be done.

尽管Armin以一个公认的答案打败了我,但我认为我应该展示一个简化的示例,说明我如何在Flask中实现regex matcher,以防有人希望看到如何实现这个示例。

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)

this URL should return with 200: http://localhost:5000/abc0-foo/

这个URL应该返回200:http://localhost:5000/abc0-foo/。

this URL should will return with 404: http://localhost:5000/abcd-foo/

这个URL应该会返回404:http://localhost:5000/abcd-foo/。

#2


47  

You can hook in custom converters that match for arbitrary expressions: Custom Converter

您可以引入与任意表达式匹配的自定义转换器:自定义转换器

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})

#3


15  

You could also write a catch all type of route and do complex routing within the method:

您还可以编写捕获所有类型的路由,并在该方法中执行复杂的路由:

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()

This will match any request. See more details here: Catch-All URL.

这将匹配任何请求。请参阅这里的详细信息:“一网打尽”URL。