Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use regular expressions to match routes

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report