Take, for example, the following two routes.
app = Flask(__name__) @app.route("/somewhere") def no_trailing_slash():
In accordance with the documents, the following is understood:
In the case of a single request to the route "/somewhere/"
, the response 404. "/somewhere"
returned.
In case of two, "/someplace/"
valid and "/someplace"
will be redirected to "/someplace/"
The behavior I would like to see is the โreverseโ behavior of two cases . for example, "/someplace/"
will be redirected to "/someplace"
, and not vice versa. Is there a way to determine the route to accept this behavior?
In my opinion, strict_slashes=False
can be set on the route to effectively use the same behavior of case two in case of one, but what I would like to do is make the redirect behavior always redirect the URL without an end slash.
One solution that I was thinking of using would be to use an error handler for 404, something like this. (Not sure if this even works)
@app.errorhandler(404) def not_found(e): if request.path.endswith("/") and request.path[:-1] in all_endpoints: return redirect(request.path[:-1]), 302 return render_template("404.html"), 404
But I am wondering if there is a better solution, for example, some some version of the application similar to strict_slashes=False
, which I can apply globally. Maybe a plan or a URL rule?
source share