python - Custom routing in Flask app -


i've been trying understand how generate dynamic flask urls. i've read docs , several example, can't figure out why code doesn't work:

path = 'foo' @app.route('/<path:path>', methods=['post']) def index(path=none):     # stuff...     return flask.render_template('index.html', path=path) 

i'd expect index.html template served /foo, not. build error. missing?

if use fixed path, /bar, works without issue.

@app.route('/bar', methods=['post'])

you've got long , short of already. need decorate view functions using /<var> syntax (or /<converter:var> syntax 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 variable out of url dynamic route you're trying use, it'll unicode string in python default. if create variable <int:var> or <float:var> converters, it'll converted appropriate type in app space you.

the <path:blah> converter match on string contains slashes (/), can pass /blah/dee/blah , path variable in view function contain string. without using path converter, flask try , dispatch request view function registered on route /blah/dee/blah, because plain <var> delineated next / in uri.

so looking @ little app, /files/<path:path> route serve whatever file find matched path sent user on request. pulled example docs here.

also, dig can specify defaults variable urls via keyword arg route() decorator.

if want, can access underlying url_map werkzeug builds based on how specify view functions , routes in app space. more stuff chew on, check out api docs on url registrations.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

debian - 500 Error upon login into Plesk Admin - auth.php3? -