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?

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):

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/


Need Your Help

Is there an "immediate window" in Visual Studio Code to run Javascript?

javascript visual-studio interpreter interactive-mode visual-studio-code

Yes, I use F12 in the browser all the time to test out Javascript snippets with the console. I'm tired of that (for the moment anyway).

Drawing colored text in UIView's -drawRect: method

ios uikit drawrect uicolor nsattributedstring

I am trying to draw colored text in my UIView subclass. Right now I am using the Single View app template (for testing). There are no modifications except the drawRect: method.