Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask URL Route: Route Several URLs to the same function

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?

like image 869
Gaby Solis Avatar asked Dec 24 '12 16:12

Gaby Solis


People also ask

Can we have multiple URL paths pointing to the same route function?

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.

Can you use multiple decorators to route URLs to a function in Flask?

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.

What does .route do in Flask?

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.

What does @APP mean in Flask?

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.


2 Answers

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): 
like image 114
Amber Avatar answered Oct 06 '22 01:10

Amber


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/

like image 32
Jon Clements Avatar answered Oct 06 '22 01:10

Jon Clements