You've got the long and short of it already. All you need to do is decorate your view functions using the /<var>
syntax (or the /<converter:var>
syntax where appropriate).
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/<word>', defaults={'word': 'bird'})
def word_up(word):
return render_template('whatstheword.html', word=word)
@app.route('/files/<path:path>')
def serve_file(path):
return send_from_directory(app.config['UPLOAD_DIR'], path, as_attachment=True)
if __name__ == '__main__':
app.debug = True
app.run(port=9017)
When Flask pulls a variable out of a URL for a dynamic route like you're trying to use, it'll be a unicode string in Python by default. If you create the variable with the <int:var>
or <float:var>
converters, it'll be converted to the appropriate type in the app space for you.
The <path:blah>
converter will match on a string that contains slashes (/
), so you can pass /blah/dee/blah
and the path variable in your view function will contain that string. Without using the path
converter, flask would try and dispatch your request to a view function registered on the route /blah/dee/blah
, because the plain <var>
is delineated by the next /
in the uri.
So looking at my little app, the /files/<path:path>
route would serve whatever file it could find that matched the path sent up by the user on the request. I pulled this example from the docs here.
Also, dig that you can specify defaults for your variable URLs via a keyword arg
to the route()
decorator.
If you want, you can even access the underlying url_map
that Werkzeug builds based on how you specify your view functions and routes in your app space. For more stuff to chew on, check out the api docs on URL registrations.