Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design Flask URL path with '/'

Tags:

python

url

flask

In my first Flask application, I am experimenting with URLs that end with a slash vs. those that don't and am seeing some unexpected browser behavior.

  1. My view function is just like this:

    @app.route('/hello')
    def hello_world():
        return 'Hello World!'
    

    Then I can go to 127.0.0.1:5000/hello and see "Hello World".

  2. I change the URL to:

    @app.route('/hello/')
    def hello_world():
        return 'Hello World!'
    

    Then I can go to 127.0.0.1:5000/hello but the browser redirects to 127.0.0.1:5000/hello/.

  3. I change the URL back to /hello:

    @app.route('/hello')
    def hello_world():
        return 'Hello World!'
    

Then I can not access either /hello or /hello/. When I visit 127.0.0.1:5000/hello, the browser still redirects to 127.0.0.1:5000/hello/ and the response is a 404. I cannot see anything unless I rollback to step 2.

What is going on?

like image 307
Xu Feng Avatar asked Dec 07 '25 07:12

Xu Feng


1 Answers

Quoting from a (slightly modified) section of the docs:

Unique URLs / Redirection Behavior

Though [your rules] look rather similar, they differ in their use of the trailing slash in the URL definition. In [your step #2], the canonical URL for the [hello_world] endpoint has a trailing slash. In that sense, it is similar to a folder on a file system. Accessing it without a trailing slash will cause Flask to redirect to the canonical URL with the trailing slash.

What this means is that Flask in step #2 will redirect the /hello URL using a 301 Moved redirect. This is a permanent redirect and most browsers will cache it. This is why, even when you change your code (in step #3) the browser will still request /hello/ even though you asked for /hello (since when it did so for step #2 Flask told it that /hello has moved to /hello/.)

The simplest solution in such cases is to clear your browser's cache - that removes the "memory" of the redirect and things will work again.

Personally, I use /directory/ style URLs for resources which would be expected to contain other resources and /leaf for resources which have no further sub-resources.

like image 176
Sean Vieira Avatar answered Dec 09 '25 18:12

Sean Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!