The Art of Routing: Variable Rules, HTTP Methods and Unique URLs
📂 Stage: Stage 1 - Breaking the ice and setting sail (Basics) 🔗 Related chapters: 初识 Flask · Jinja2 模板引擎
Routing, in a nutshell, is a mechanism that binds the URL path visited by the browser to the Python processing function we wrote. Flask's routing system is flexible and simple, which is one of the core reasons why it is quick to use and popular. Today we will go through this basic but crucial module together.
1. Start with the simplest route
1.1 Basic decorator writing method
Flask uses@app.route()Decorator to define routes, the parameter is the URL path you want to bind. Let’s write the most intuitive code first:
After starting, access in the browserhttp://127.0.0.1:5001andhttp://127.0.0.1:5001/about, you can see the corresponding page.
1.2 The "icing" principle of decorators (simple version)
Many novices may find decorators mysterious, but in Flask routing, they are just syntax sugar—essentially registering functions into the application’s routing map.
It is enough to understand this principle. In daily development, you should still use decorators directly. The code is concise and easy to read.
2. Dynamic routing: let the URL have "variables"
static/aboutOnly fixed content can be displayed. If you want to display articles from different users’ personal homepages and IDs, it’s impossible to write thousands of them.@app.route("/user/john")Bar? At this time, you need path variables, which is dynamic routing.
2.1 The three most commonly used ways to write variables
2.2 Complete variable type cheat sheet
inanyConverters are great for handling "fixed options but don't want to write multiple routes" scenarios:
2.3 Multiple variable combinations (blog archive example)
Variables can be combined in any way as long as they comply with the URL specification:
3. HTTP method: Control the "action" of the request
The browser sends it by default by pressing Enter in the address bar.GETrequest, but there is much more to web development than just that. Also commonly used arePOST、PUT、DELETEetc., they essentially tell the server "what do you want to do with this resource".
3.1 Multi-method binding (login form example)
The login function usually requires two actions: usingGETTo display the form, usePOSTSubmit the form. we can passmethodsParameters allow the same route to handle both requests.
💡 Tips:
request.formSpecifically used to obtain form data submitted by POST; if the upload is JSON, you can userequest.get_json()。
3.2 RESTful style routing design
REST is currently the most popular API design principle. The core concept is: URL describes resources, and HTTP methods describe operations. Take the "article" resource as an example:
⚠️ Note: The browser only supports nativeGETandPOST, if you want to send it in an HTML formPUT、PATCH、DELETERequest, you need to use hidden fields<input type="hidden" name="_method" value="PUT">And cooperate with Flask'smethodoverrideMiddleware (will be expanded on in subsequent chapters).
4. URL reverse generation: Say goodbye to the trouble of hard coding
Hardcoding URLs is a big no-no in development. For example, if you/aboutchanged to/about-us, all places that reference this address (HTML links, redirect codes) must be modified one by one, and it is easy to miss. Flask providesurl_forfunction, generate the corresponding URL through the name of the view function, which perfectly solves this problem.
4.1 url_forBasic usage of
4.2 Use with Jinja2 template
In actual development, links are mostly written in Jinja2 templates, and their usage is almost the same as Python code:
💡 Best Practice: Use it unconditionally whenever you need to generate URLs inside your application
url_for, which will make refactoring incredibly easy.
5. Unique URLs: Flask’s “smart” trailing slash handling
Have you noticed that visitinghttps://flask.palletsprojects.com/andhttps://flask.palletsprojects.comIt's the same page, but visit/about/and/aboutMaybe the behavior is different? Flask handles trailing slashes carefully to avoid the SEO embarrassment of "two URLs for the same resource".
5.1 Flask’s default behavior
Test it out:
- Visit
/about→ ✅Return normally - Visit
/about/→ 🔀 Flask automatically 301 redirects to/about - Access
/blog/→ ✅Return normally - Access
/blog→ 🔀 Flask automatically 301 redirects to/blog/
Flask's approach is: if the route defined does not have a slash, access to the address with a slash will be redirected to the version without a slash; and vice versa. This always ensures that there is only one authoritative address for a resource.
5.2 Should I add a trailing slash?
It is recommended to follow the following intuition:
- Static pages (such as
/about、/contact)→ without slash, like file - List/collection pages (e.g.
/blog/、/users/) → Add slash, like a folder - API interface (e.g.
/api/articles、/api/users/123)→ Uniform without slash, more concise
6. Summary
Today we systematically learned the core capabilities of Flask routing:
- Basic Decorator:
@app.route("/path")Bind URL to view function - Dynamic Routing:
<converter:variable>Let URLs carry mutable data - HTTP Method: Pass
methodsParameters handle different request actions, moving towards RESTful design - Reverse generation:
url_for("view_name", arg=val)Eliminate hard coding - Unique URL: Understand Flask’s trailing slash redirection mechanism
💡 Core design principle: URLs should be predictable, descriptive of the resource, and unique.
🔗 Extended reading

