56

我正在使用 Flask 0.9。

现在我想将三个 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):

会有更好的解决方案吗?

4

2 回答 2

116

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

@app.route('/item/<int:appitemid>/')
@app.route('/item/<int:appitemid>/<path:anythingcanbehere>')
def show_item(appitemid, anythingcanbehere=None):
于 2012-12-24T16:32:31.703 回答
16

是的 - 您使用以下构造:

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

请参阅http://flask.pocoo.org/snippets/57/上的片段

于 2012-12-24T16:33:17.430 回答