Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Flask support regular expressions in its URL routing?

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

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

like image 588
Alistair Avatar asked May 03 '11 13:05

Alistair


People also ask

What is URL routing in Flask?

App routing is used to map the specific URL with the associated function that is intended to perform some task. It is used to access some particular page like Flask Tutorial in the web application.

What is a regular expression URL?

URL regular expressions can be used to verify if a string has a valid URL format as well as to extract an URL from a string.

How does a Flask routing work?

App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. Example: In our application, the URL (“/”) is associated with the root URL.


2 Answers

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) 

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

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

like image 179
Philip Southam Avatar answered Sep 17 '22 23:09

Philip Southam


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}) 
like image 37
Armin Ronacher Avatar answered Sep 18 '22 23:09

Armin Ronacher