Flask URL Route:将多个 URL 路由到同一个函数 [英] Flask URL Route: Route Several URLs to the same function

查看:116
本文介绍了Flask URL Route:将多个 URL 路由到同一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Flask 0.9.

I am working with Flask 0.9.

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

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?

推荐答案

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

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

这篇关于Flask URL Route:将多个 URL 路由到同一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆