烧瓶URL路线:将几个URL路由到同一功能

发布于 2025-01-25 13:40:20 字数 507 浏览 3 评论 0原文

我正在使用烧瓶0.9。

现在,我想将三个URL路由到相同的函数:

/item/<int:appitemid>
/item/<int:appitemid>/ 
/item/<int:appitemid>/<anything can be here>

&lt;任何东西都可以在这里&gt;零件永远不会在该功能中使用。

我必须两次复制相同的功能才能实现此目标:

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

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

会有更好的解决方案吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜巴黎 2025-02-01 13:40:20

为什么不使用可能为空的参数,默认值none

@app.route('/item/<int:appitemid>/')
@app.route('/item/<int:appitemid>/<path:anythingcanbehere>')
def show_item(appitemid, anythingcanbehere=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):
时间海 2025-02-01 13:40:20

是的 - 您使用以下结构:

@app.route('/item/<int:appitemid>/<path:path>')
@app.route('/item/<int:appitemid>', defaults={'path': ''})

Yes - you use the following construct:

@app.route('/item/<int:appitemid>/<path:path>')
@app.route('/item/<int:appitemid>', defaults={'path': ''})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文