Understanding Flask URL Routing and View Functions
This article explains Flask's URL routing mechanisms, covering the route decorator and add_url_rule methods, static and dynamic routes, variable types, and how to use url_for for reverse URL generation and static file linking.
In the previous chapter "Flask Intro Series 03 - Database Operations" we covered Flask's database features. This article introduces how URLs map to view functions in Flask.
URL and View Corresponding Methods
Flask provides two common ways to bind URLs to view functions: the @app.route decorator and the app.add_url_rule method.
1. Route Decorator
The route decorator is used by placing @app.route('/del_schedule') above a function definition:
@app.route('/del_schedule') def del_schedule(): return 'ok'
The decorator receives the URL rule as a parameter, which determines the association between the URL and the function. Internally it creates a Rule object and registers it in Flask's URL map, using the function name as the endpoint.
2. add_url_rule Method
The add_url_rule method achieves the same binding by explicitly passing the rule and endpoint:
def del_schedule(): return 'ok' app.add_url_rule('/', 'del_schedule', del_schedule)
Static vs. Dynamic Routes
Routes can be static (fixed URL) or dynamic (URL contains variables). Flask supports variable types such as string (default, no slash), int , float , path (allows slashes), and uuid . Example of a dynamic route:
@app.route('/post/ ')
Here other_path is passed to the view function as a parameter.
Constructing URLs with url_for
The url_for function performs reverse URL lookup, generating the URL for a given view function. For example, url_for('del_schedule') returns the URL bound to del_schedule . It is also commonly used to reference static files:
<link href="{{ url_for('static', filename='css/styles.css') }}" rel="stylesheet">
Conclusion
This overview covered the basic relationship between Flask URLs and view functions, including the route decorator, add_url_rule , static and dynamic routes, variable types, and reverse URL generation with url_for . Future articles will explore Flask authentication.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.