Routing in Flask
Archive - Originally posted on "The Horse's Mouth" - 2015-10-11 11:17:30 - Graham EllisHaving got "hello world" working on your server in Flask (see [here] if you haven't!), you'll want to add further routes for other URLs - and indeed you'll want those routes to contain match markers so you can set up whole families of URLs. Our first example included:
@app.route("/")
def hello():
etc
and we'll now add some further routes (using the route decorator):
@app.route("/<word>")
def greet(word):
return "This is the page called {0:s} under flask".format(word)
@app.route("/<folder>/<word>")
def greeting(folder,word):
return "This is the page called {0:s} in the {1:s} folder".format(word,folder)
Sample outputs:


and you can also include rules such as
@app.route('/post/<int:post_id>')
which will only match an integer. Also float and path are available - for a floating point number, and for a complete path including "/" which isn't allowed by the default.
The routes above are included in our sample program [here] - which also runs the Flask application with an extra parameter "debug=True"; this replaces the default error messages with something longer and more meaningful ... which will also reveal to a knowledgable user to your site rather more about how the site works if (s)he finds a broken page. You have been warned!
Here's the error that's on the server log (I added a deliberate mistake to cause this):
192.168.200.42 - - [11/Oct/2015 11:08:09] "GET /arthur HTTP/1.1" 500 -
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
[snip]
TypeError: greet() takes exactly 2 arguments (1 given)
and here's the display to the user (this is just the top of the page - scroll down for more!)

The routing and more is base on Werkzeug- http://werkzeug.pocoo.org - and the whole comes together with much more in Full Stack Python - http://www.fullstackpython.com/flask.html.