Flask 在其 URL 路由中是否支持正则表达式? [英] Does Flask support regular expressions in its URL routing?

查看:37
本文介绍了Flask 在其 URL 路由中是否支持正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有没有一种方法可以使用正则表达式,就像在 Django 中一样?

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

推荐答案

尽管 Armin 用一个公认的答案打败了我,但我想我还是会展示一个我如何在 Flask 中实现正则表达式匹配器的简短示例,以防万一任何人都想要一个如何做到这一点的工作示例.

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.

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/

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

此 URL 将返回 404:http://localhost:5000/abcd-foo/

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

这篇关于Flask 在其 URL 路由中是否支持正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆