首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Flask URL路由:将多个URL路由到同一函数

Flask URL路由:将多个URL路由到同一函数
EN

Stack Overflow用户
提问于 2012-12-25 00:27:04
回答 2查看 30.6K关注 0票数 54

我正在使用Flask 0.9。

现在我想将三个urls路由到同一个函数:

代码语言:javascript
复制
/item/<int:appitemid>
/item/<int:appitemid>/ 
/item/<int:appitemid>/<anything can be here>

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

为了实现这个目标,我必须将同一个函数复制两次:

代码语言:javascript
复制
@app.route('/item/<int:appitemid>/')
def show_item(appitemid):

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

会有更好的解决方案吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-25 00:32:32

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

代码语言:javascript
复制
@app.route('/item/<int:appitemid>/')
@app.route('/item/<int:appitemid>/<path:anythingcanbehere>')
def show_item(appitemid, anythingcanbehere=None):
票数 112
EN

Stack Overflow用户

发布于 2012-12-25 00:33:17

Yes -使用以下结构:

代码语言:javascript
复制
@app.route('/item/<int:appitemid>/<path:path>')
@app.route('/item/<int:appitemid>', defaults={'path': ''})

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

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14023664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档