Trailing a slash in a bulb

Take, for example, the following two routes.

app = Flask(__name__) @app.route("/somewhere") def no_trailing_slash(): #case one @app.route("/someplace/") def with_trailing_slash(): #case two 

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?

+10
source share
2 answers

You are on the right track with strict_slashes , which you can configure in the Flask app itself. This will set the strict_slashes flag to False for each route created.

 app = Flask('my_app') app.url_map.strict_slashes = False 

Then you can use before_request to detect the before_request / for redirection. Using before_request will allow you not to require special logic for each individual route.

 @app.before_request def clear_trailing(): from flask import redirect, request rp = request.path if rp != '/' and rp.endswith('/'): return redirect(rp[:-1]) 
+18
source

If you want both routes to be handled the same way, I would do this:

 app = Flask(__name__) @app.route("/someplace/") @app.route("/someplace") def slash_agnostic(): #code for both routes 
0
source

Source: https://habr.com/ru/post/1011918/


All Articles