Trailing slash in Flask route

后端 未结 3 1274
太阳男子
太阳男子 2020-12-01 16:27

Take for example the following two routes.

app = Flask(__name__)

@app.route(\"/somewhere\")
def no_trailing_slash():
    #case one

@app.route(\"/someplace/         


        
相关标签:
3条回答
  • You can also use the option strict_slashes=False in your route definition:

    app.Flask(__name__)
    @app.route("/someplace", strict_slashes=False)
    # Your code goes here
    
    0 讨论(0)
  • 2020-12-01 16:38

    You are on the right tracking with using strict_slashes, which you can configure on the Flask app itself. This will set the strict_slashes flag to False for every route that is created

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

    Then you can use before_request to detect the trailing / for a redirect. Using before_request will allow you to not require special logic to be applied to each route individually

    @app.before_request
    def clear_trailing():
        from flask import redirect, request
    
        rp = request.path 
        if rp != '/' and rp.endswith('/'):
            return redirect(rp[:-1])
    
    0 讨论(0)
  • 2020-12-01 16:54

    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 讨论(0)
提交回复
热议问题