Flask URL Route: Route Several URLs to the same function

谁说胖子不能爱 提交于 2019-12-18 01:26:13

问题


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?


回答1:


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):



回答2:


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/



来源:https://stackoverflow.com/questions/14023664/flask-url-route-route-several-urls-to-the-same-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!