2012-12-24 115 views
16

我正在使用Flask 0.9。烧瓶URL路由:路由几个URL到相同的功能

现在我想航线三个URL相同的功能:

/item/<int:appitemid> 
/item/<int:appitemid>/ 
/item/<int:appitemid>/<anything can be here> 

<anything can be here>部分永远不会在函数中使用。

我必须复制相同功能的两倍来实现这一目标:

@app.route('/item/<int:appitemid>/') 
def show_item(appitemid): 

@app.route('/item/<int:appitemid>/<path:anythingcanbehere>') 
def show_item(appitemid, anythingcanbehere): 

会不会有更好的解决办法?

回答

45

为什么不使用可能为空的参数,默认值为None

@app.route('/item/<int:appitemid>/') 
@app.route('/item/<int:appitemid>/<path:anythingcanbehere>') 
def show_item(appitemid, anythingcanbehere=None): 
+0

非常简单,直观,有效的解决方案。 – tmthyjames

4

是 - 您使用下面的结构:

@app.route('/item/<int:appitemid>/<path:path>') 
@app.route('/item/<int:appitemid>', defaults={'path': ''}) 

看到的片段在http://flask.pocoo.org/snippets/57/