Gab*_*lis 34 python url-routing flask
我正在使用Flask 0.9.
现在我想将三个URL路由到同一个函数:
/item/<int:appitemid>
/item/<int:appitemid>/
/item/<int:appitemid>/<anything can be here>
Run Code Online (Sandbox Code Playgroud)
该<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):
Run Code Online (Sandbox Code Playgroud)
会有更好的解决方案吗?
Amb*_*ber 76
为什么不使用可能为空的参数,默认值为None?
@app.route('/item/<int:appitemid>/')
@app.route('/item/<int:appitemid>/<path:anythingcanbehere>')
def show_item(appitemid, anythingcanbehere=None):
Run Code Online (Sandbox Code Playgroud)
是的 - 您使用以下构造:
@app.route('/item/<int:appitemid>/<path:path>')
@app.route('/item/<int:appitemid>', defaults={'path': ''})
Run Code Online (Sandbox Code Playgroud)
请参阅http://flask.pocoo.org/snippets/57/上的摘录