62

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?

Gaby Solis
  • 2,427
  • 5
  • 21
  • 27

2 Answers2

128

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):
Amber
  • 507,862
  • 82
  • 626
  • 550
17

Yes - you use the following construct:

@app.route('/item/<int:appitemid>/<path:path>')
@app.route('/item/<int:appitemid>', defaults={'path': ''})
mirekphd
  • 4,799
  • 3
  • 38
  • 59
Jon Clements
  • 138,671
  • 33
  • 247
  • 280