SoFunction
Updated on 2025-04-06

Implementation code for regular expression matching routes

In web development, there may be scenarios where users access rules may be restricted. At this time, regular matching is needed, and the request parameters are limited according to their own rules before accessing.

The specific implementation steps are:

  • Import converter base class: In Flask, all route matching rules are recorded using converter objects
  • Custom converter: Custom class inherits from converter base class
  • Add converter to default converter dictionary
  • Implement custom matching rules with custom converters

Code implementation

Import the converter base class

from import BaseConverter

Custom converter

# Custom regular converterclass RegexConverter(BaseConverter):
  def __init__(self, url_map, *args):
    super(RegexConverter, self).__init__(url_map)
    # Save the first parameter accepted as a matching rule     = args[0]

Add a converter to the default converter dictionary and specify that the converter is used as: re

app = Flask(__name__)
# Add a custom converter to the converter dictionary and specify that the converter's name is: reapp.url_map.converters['re'] = RegexConverter

Use a converter to implement custom matching rules

The current rule defined here is: 3 digits

@('/user/<re("[0-9]{3}"):user_id>')
def user_info(user_id):
  return "user_id is %s" % user_id

Run the test:http://127.0.0.1:5000/user/123, If the URL you visited does not comply with the rules, the page will not be found

System comes with converter

DEFAULT_CONVERTERS = {
  'default':     UnicodeConverter,
  'string':      UnicodeConverter,
  'any':       AnyConverter,
  'path':       PathConverter,
  'int':       IntegerConverter,
  'float':      FloatConverter,
  'uuid':       UUIDConverter,
}

The specific usage method of the system's own converter is written in the annotation code of each converter. Pay attention to the initialization parameters of each converter.

Summarize

The above is the implementation code of regular expression matching route introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!