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

Python 在构建要路由的url时处理空参数,python,flask,Python,Flask,我的应用程序有一个产品模型。有些产品有类别,有些没有。在我的其中一页中,我将有以下内容: {% 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_cat

我的应用程序有一个产品模型。有些产品有类别,有些没有。在我的其中一页中,我将有以下内容:

{% 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 %}
{%if row.category%}
{%else%}
{%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 ....
@app.route('/',方法=['GET'])
def详细信息和类别(类别、标题):
....
返回。。。。
@app.route('/',方法=['GET'])
def详细信息(无类别)(标题):
....
返回。。。。

带有类别的
details\u
和不带类别的
details\u
做的事情完全相同,只是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
@app.route('/',默认值={'category':''})
@应用程序路径(“/”)
def详细信息(标题、类别):
#...
url_用于('details',category='Python',title='Flask')
#/details/Python/Flask
url_用于('details',title='Flask')
#/详细信息/烧瓶
url_用于('details',category='',title='Flask')
#该类别与默认类别匹配,因此将忽略该类别
#/详细信息/烧瓶

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