Python Flask URL Route:将多个 URL 路由到同一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14023664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask URL Route: Route Several URLs to the same function
提问by Gaby Solis
I am working with Flask 0.9.
我正在使用 Flask 0.9。
Now I want to route three urls to the same function:
现在我想将三个 url 路由到同一个函数:
/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.
该<anything can be here>部件永远不会在函数中使用。
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?
会有更好的解决方案吗?
采纳答案by Amber
Why not just use a parameter that can potentially be empty, with a default value of None?
为什么不只使用一个可能为空的参数,默认值为None?
@app.route('/item/<int:appitemid>/')
@app.route('/item/<int:appitemid>/<path:anythingcanbehere>')
def show_item(appitemid, anythingcanbehere=None):
回答by Jon Clements
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/

