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

Dra*_*mal 3 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_category", title=row.title) }}"> row.prod_title</a>
{% endif %}
Run Code Online (Sandbox Code Playgroud)

处理此问题的视图是:

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

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

两者details_with_categorydetails_without_category做同样的事情,只是使用不同的网址.有没有办法将视图组合成一个视图,在构建URL时采用可选参数?

dav*_*ism 5

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

@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
Run Code Online (Sandbox Code Playgroud)

更简洁的解决方案是将默认类别分配给未分类的产品,以使网址格式保持一致.