Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use regular expressions to match routes

Shulou Source: shulou.com Published: 2022-06-02 11:28:35 10月04日 Update

This article shows you how to use regular expressions to match routes, the content is concise and easy to understand, can definitely brighten your eyes, through the detailed introduction of this article, I hope you can get something.

The specific implementation steps are:

Import converter base class: in Flask, all routing matching rules are recorded using converter objects

Custom converter: the custom class inherits from the converter base class

Add a converter to the default converter dictionary

Using custom converters to implement custom matching rules

Code implementation

Import converter base class

From werkzeug.routing import BaseConverter

Custom converter

# Custom regular converter class RegexConverter (BaseConverter): def _ init__ (self, url_map, * args): super (RegexConverter, self). _ _ init__ (url_map) # save the first parameter accepted as a matching rule self.regex = args [0]

Add the converter to the default converter dictionary and specify that the converter is used with the name: re

App = Flask (_ _ name__) # adds a custom converter to the converter dictionary and specifies that the name of the converter when used is: reapp.url_map.converters ['re'] = RegexConverter

Use converters to implement custom matching rules

The rule currently defined here is: 3 digits

@ app.route ('/ user/') 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 accessed does not conform to the rules, it will prompt that the page cannot be found.

The system has its own converter

DEFAULT_CONVERTERS = {'default': UnicodeConverter,' string': UnicodeConverter, 'any': AnyConverter,' path': PathConverter, 'int': IntegerConverter,' float': FloatConverter, 'uuid': UUIDConverter,} this is how to use regular expressions to match routes. have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Tags: Converters rules regular routes dictionaries expressions content names skills knowledge concise concise code parameters objects that is numbers articles more steps Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft vpn MariaDB Xiaomi Linux