Flask quickstart example - 404 with trailing slash

243 views Asked by At

I am going through the Flask quickstart guide, but the examples of routing with variables do not work for me.

from flask import Flask
app = Flask(__name__)

@app.route('/') # fine
def index():
    return 'Index Page'

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

@app.route('/user/<username>') # <- fails unless trailing slash here
def show_user_profile(username):
    return 'User {}'.format(username)

if __name__ == '__main__':
    app.run()

I have also tried the code exactly as in the guide. Is the error in my first bullet point expected? Is code in the quickstart version supposed to work? Or have I misunderstood something?

I'm using Python 2.7.10, Flask 0.10.1, Werkzeug 0.10.4

2

There are 2 answers

1
Cassum On

I tried out this example in python2 and it works fine, but in python3 problem you described occurs. Are you using 3rd version? And if you do are you sure you really need it?

Look at this http://flask.pocoo.org/docs/0.10/python3/#python3-support

2
Pralhad Narsinh Sonar On

This code has worked on my machine with Python 2.7 on it.

In case you are using multiple parameters then you missed {0} in your code.

from flask import Flask
app = Flask(__name__)

@app.route('/') # fine
def index():
    return 'Index Page'

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

@app.route('/user/<username>') # <- fails unless trailing slash here
def show_user_profile(username):
    if request.url[-1] != '/':
        return redirect(request.url + '/')
    return 'User {0}'.format(username)

if __name__ == '__main__':
    app.run()

As you will observe I have added two more lines of code

    if request.url[-1] != '/':
        return redirect(request.url + '/')

The lines above will ensure that routes with trailing slash will still work. You will need manipulate any other path instead of / in case it is required. Please try this code.