-
Sometimes defining a route the default path values can be set for the user convenience. Firstly, I have asked a question about it on StackOverflow. But no other way to override has been introduced. (It is a simplified example that reproduce the problem.) I have I want to generate the following URL: The most obvious to me approach: The next approach:
The next approach: I have also tried the approach from this answer but Firstly, I have tested it on The only way not changing Flask I come up with is |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
It will be possible to override the behavior of class MyFlask(Flask):
def url_for(self, endpoint, **kwargs):
if endpoint == "api_items":
kwargs.setdefault("a", "A0")
kwargs.setdefault("b", "B0")
return super().url_for(endpoint, **kwargs) This is probably not a good idea, it's likely less efficient to check every call to see if it's for one endpoint than to use multiple rules and let the router take care of it. |
Beta Was this translation helpful? Give feedback.
-
This comes from a misunderstanding of how
So you would use defaults to create a default URL that does not have those corresponding variables, and it would be routed to the correct endpoint with those defaults. It will also generate the short URL if the default values are given, and will redirect to the short URL if the default URL is given. It will not fill in missing values, or allow overriding the variables of a single rule. It requires both a Rule with the defaults (and no variables), and a Rule with the variables. Here's how you could use four rules to allow the behavior you want, overriding any combination of the variables. Typically though, you wouldn't write the default values in the URL still, you'd do what the example in the docs above show and have a default rule with no values in the URL. @app.route("/api/A0/B0", defaults={"a": "A0", "b": "B0"})
@app.route("/api/<a>/B0", defaults={"b": "B0"})
@app.route("/api/A0/<b>", defaults={"a": "A0"})
@app.route("/api/<a>/<b>")
def api_items(a, b):
return f"{a=}, {b=}" |
Beta Was this translation helpful? Give feedback.
This comes from a misunderstanding of how
defaults
works in Werkzeug's router. From the docs forwerkzeug.routing.Rule
:So you would use d…