构建 url 路由时处理空参数

Handle empty parameters when building url to route

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

{% 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 %}

处理此问题的视图是:

@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 不同。在构建 url?

时,有没有一种方法可以将视图组合成一个带有可选参数的视图

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

@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 格式保持一致。