Search code examples
flaskflask-restful

What difference between URL paths in Flask?


What difference between URL paths:

@app.route('/projects')

@app.route('/projects/')

What does mean slash in the end of route path? In witch cases to use it?

If I understood correctly it is used for absolute and relative path to server files? Right?


Solution

  • This is called trailing slash.

    For general trailing slash,

    1. https://www.google.com/example/ -> It's a directory.

      • Firtst, Server checks if the directory exists.
      • Second, If it exists, server checks default file, such as index.html
    2. https://www.google.com/example -> It's a file.

      • Firtst, Server checks if the file exists.
      • Second, if not, check the directory with that name.

    Therefore, if you specify a trailing slash when requesting a directory resource, there is a small gain in page response speed because you can skip file checking.

    In Flask

    1. @app.route('/projects')

      • call to /projects/ -> return 404.
        (Werkzeug interprets as an explicit rule, so it's not match a trailing slash.)
      • call to /projects -> return 200
    2. @app.route('/projects/')

      • call to /projects/ -> return 200
      • call to /projects -> return 302
        (Werkzeug will redirect if the url doesn't have it)

    This article will be helpful.