I am working with Flask 0.9.
Now I want to route three urls to the same function:
/item/<int:appitemid> /item/<int:appitemid>/ /item/<int:appitemid>/<anything can be here>
The <anything can be here>
part will never be used in the function.
I have to copy the same function twice to achieve this goal:
@app.route('/item/<int:appitemid>/') def show_item(appitemid): @app.route('/item/<int:appitemid>/<path:anythingcanbehere>') def show_item(appitemid, anythingcanbehere):
Will there be a better solution?
In some cases you can reuse a Flask route function for multiple URLs. Or you want the same page/response available via multiple URLs. In that case you can add a second route to the function by stacking a second route decorator to the function. The code below shows how you use the a function for multiple URLs.
The decorator syntax is just a little syntactic sugar. This code block shows an example using our custom decorator and the @login_required decorator from the Flask-Login extension. We can use multiple decorators by stacking them.
Routing in Flask The route() decorator in Flask is used to bind an URL to a function. As a result when the URL is mentioned in the browser, the function is executed to give the result.
The @ is telling Python to decorate the function index() with the decorator defined in app. route() . Basically, a decorator is a function that modifies the behaviour of another function. As a toy example, consider this.
Why not just use a parameter that can potentially be empty, with a default value of None
?
@app.route('/item/<int:appitemid>/') @app.route('/item/<int:appitemid>/<path:anythingcanbehere>') def show_item(appitemid, anythingcanbehere=None):
Yes - you use the following construct:
@app.route('/item/<int:appitemid>/<path:path>') @app.route('/item/<int:appitemid>', defaults={'path': ''})
See the snippet at http://flask.pocoo.org/snippets/57/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With