YouTip LogoYouTip

Flask Router

Routing is one of the core features of a Web framework, which determines which URL is handled by which function. Flask routing is the mechanism in Web applications that maps URLs to Python functions. Flask routing is the core part of Flask applications, used to handle requests for different URLs and delegate the request handling to the corresponding view functions. The following is a detailed explanation of Flask routing, including route definition, parameters, methods, and rules, etc. * * * ## Basic Routing Use the @app.route() decorator to bind a URL path to a view function: ## Example from flask import Flask app = Flask( __name__ ) # Bind the root path "/" @app.route("/") def index(): return" This is the homepage" # Bind the "/hello" path @app.route("/hello") def hello(): return"Hello, TUTORIAL!" # Different paths correspond to different functions @app.route("/about") def about(): return"About this site" When accessing http://127.0.0.1:5000/hello, Flask calls the hello() function. When accessing http://127.0.0.1:5000/about, Flask calls the about() function. !(#) * * * ## Variable Rules In practical applications, URLs often contain dynamic parts, such as user IDs, article titles, etc. Flask uses the syntax to define dynamic parts in URLs, and the corresponding parameters are automatically passed to the view function. ### String Variable (Default Type) When no type is specified, the variable defaults to a string, matching any character except a slash /: ## Example # is a dynamic variable, Flask passes its value as a keyword parameter to the view function @app.route("/user/") def show_user(username): # Note: username may contain malicious scripts, need to escape in production return f"

User: {username}

" # Test access: # /user/tutorial β†’ page displays "User: tutorial" # /user/TUTORIAL β†’ page displays "User: TUTORIAL" ### Type Converters Flask has built-in multiple converters, specified using the syntax: | Converter | Description | Example URL | Match Result | | --- | --- | --- | --- | | string | Default, accepts text without / | /user/tutorial | username = "tutorial" | | int | Positive integer | /post/42 | post_id = 42 | | float | Positive float | /price/19.99 | price = 19.99 | | path | Accepts strings containing / | /file/a/b/c.txt | filepath = "a/b/c.txt" | | uuid | UUID format string | /item/550e8400-e29b-41d4-a716-446655440000 | item_id = UUID string | ## Example # int converter: only numbers can match, /post/abc will return 404 @app.route("/post/") def show_post(post_id): # post_id is of type int, not string return f"

Article #{post_id}

" # path converter: can match paths containing / @app.route("/file/") def show_file(filepath): return f"

File path: {filepath}

" # float converter: matches floating point numbers @app.route("/price/") def show_price(amount): return f"

Price: Β₯{amount}

" # uuid converter: only accepts standard UUID format @app.route("/item/") def show_item(item_id): return f"

Item ID: {item_id}

" > Converters not only perform type validation but also automatically convert matched values to the corresponding Python type. For example, passes an int to the view function instead of a str. * * * ## Trailing Slash Redirect Behavior The presence or absence of a trailing / in URLs has a direct impact on route matching behavior, which confuses many beginners. ## Example # Rule 1: ends with / β€” similar to a directory # Accessing /projects will automatically 308 redirect to /projects/ @app.route("/projects/") def projects(): return"Project list page" # Rule 2: does not end with / β€” similar to a file # Accessing /about/ will return 404 Not Found @app.route("/about") def about(): return"About page" | Route Definition | Access /projects | Access /projects/ | | --- | --- | --- | | @app.route("/projects/") | 308 redirect to /projects/ | Normal return | | @app.route("/about") | Normal return | 404 Not Found | > This design helps with SEO: ensuring each content has only one standard URL, avoiding search engines indexing the same page twice. * * * ## URL Building β€” url_for url_for() is Flask's built-in URL generation function that generates the corresponding URL based on the view function name. This has many advantages over hardcoding URL strings: * If the URL route is modified later, all places generated by url_for will automatically update * Automatically handles escaping of special characters * Generated paths are always absolute paths ## Example from flask import Flask, url_for app = Flask( __name__ ) @app.route("/") def index(): return"Homepage" @app.route("/login") def login(): return"Login page" @app.route("/user/") def profile(username): return f"{username}'s profile" # Use test_request_context() to simulate a request context # This allows url_for() to correctly generate URLs with app.test_request_context(): print(url_for("index"))# Output / print(url_for("login"))# Output /login print(url_for("login", next="/"))# Output /login?next=%2F print(url_for("profile", username="tutorial"))# Output /user/tutorial The first parameter of url_for() is the view function name (note: it's the function name, not the URL path). If the URL
← Flask TemplatesFlask Basic Concept β†’