我的应用有产品型号。有些产品有类别,有些没有。在我的一个页面中,我将有这个:
{% 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_category
和details_without_category
都做同样的事情,只是使用不同的网址。有没有办法将视图组合成一个视图,在构建URL时采用可选参数?
答案 0 :(得分: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
更清洁的解决方案是将默认类别分配给未分类的产品,以使网址格式保持一致。