Sometimes, we want to use regular expressions with Python Flask URL routing.
In this article, we’ll look at how to use regular expressions with Python Flask URL routing.
How to use regular expressions with Python Flask URL routing?
To use regular expressions with Python Flask URL routing, we can create our own convert class.
For instance, we wrire
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)
to create the RegexConverter class that sets self.regex to the first items entry.
Then we register the regex converter with
app.url_map.converters['regex'] = RegexConverter
Then if our URL starts with <regex and ends with > then RegexConverter will be used to match URLs.
Conclusion
To use regular expressions with Python Flask URL routing, we can create our own convert class.