【发布时间】:2022-01-24 23:43:10
【问题描述】:
我有一个带有 GET 处理程序的 Flask 应用程序,该程序将配方 ID 作为 URL 参数,它从数据库中检索配方,然后呈现它:
@app.route('/recipe/<int:id>', methods=['GET'])
def get(id):
recipe = get_recipe_from_db(id)
return render_template('recipe.html', recipe=recipe)
这会产生一个类似/recipe/5 的网址。我希望配方标题成为结果 URL 的一部分,而不是只显示 URL 中的 id,例如recipe/5/lemon-cake。在第一个请求中,只有 id 是已知的。
我不确定这样做的好方法是什么。到目前为止,我想出了以下几点:
@app.route('/recipe/<int:id>', methods=['GET'])
def get(id):
recipe = get_recipe_from_db(id)
return redirect(url_for('get_with_title', id=id, title=urlify(recipe.title)))
@app.route('/recipe/<int:id>/<title>', methods=['GET'])
def get_with_title(id, title=None):
recipe = get_recipe_from_db(id)
return render_template('recipe.html', recipe=recipe)
这可行(即,当用户访问 /recipe/5 时,它会重定向到 /recipe/5/lemon-cake),但会遇到从数据库中检索到相同配方两次的事实。
有没有更好的方法来解决这个问题?
注意:recipe 对象很大,包含多个字段,我不想不必要地通过网络传递它。
【问题讨论】:
标签: python python-3.x flask