gpt4 book ai didi

python - 在构建要路由的 url 时处理空参数

转载 作者:太空宇宙 更新时间:2023-11-03 14:20:50 24 4
gpt4 key购买 nike

我的应用有一个产品模型。有些产品有类别,有些则没有。在我的一个页面中,我将有这个:

{% if row.category %}
<a href="{{ url_for("details_with_category", category=row.category, title=row.title) }}"> row.prod_title</a>
{% else %}
<a href="{{ url_for("details_without_category", title=row.title) }}"> row.prod_title</a>
{% endif %}

处理这个的 View 是:

@app.route('/<category>/<title>', methods=['GET'])
def details_with_category(category, title):
....
return ....

@app.route('/<title>', methods=['GET'])
def details_without_category(title):
....
return ....

details_with_categorydetails_without_category 做完全相同的事情,只是使用不同的 url。有没有一种方法可以将这些 View 组合成一个在构建 url 时采用可选参数的 View ?

最佳答案

将多个路由应用于同一函数,为可选参数传递一个默认值。

@app.route('/<title>/', defaults={'category': ''})
@app.route('/<category>/<title>')
def details(title, category):
#...

url_for('details', category='Python', title='Flask')
# /details/Python/Flask

url_for('details', title='Flask')
# /details/Flask

url_for('details', category='', title='Flask')
# the category matches the default so it is ignored
# /details/Flask

更简洁的解决方案是为未分类的产品分配一个默认类别,以便 url 格式保持一致。

关于python - 在构建要路由的 url 时处理空参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28203252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com