Flask 可选路由在 URL 中添加 /None/None
我一直在尝试设置一些可选参数,如下所示。用户应该能够浏览层次结构中任意位置的前 100 名、州或城市。
@app.route("/guide", defaults={'state': None, 'city': None})
@app.route("/guide/<state>", defaults={'state': None})
@app.route("/guide/<state>/<city>")
def guide_route(state, city):
if state == 'top_100':
return render_template('top_100.html')
elif state:
return render_template('state.html', data={'state': state})
elif state and city:
return render_template('city.html', data={'state': state, 'city': city})
else:
return render_template('something_else.html')
但是,当我在网络浏览器中访问 /guide/top_100
或 /guide
时,它会将我重定向到 /guide/None/None
是 404。同样有趣的是,我现在已将 print 语句放入 guide_route()
函数的每个部分中,但它们都没有触发。所以路由表中的某些东西根本不起作用。
如何让这些可选参数发挥作用?
I've been trying to set up some optional parameters like below. The user should be able to browse either the top 100, the states or the cities at any point in the heirarchy.
@app.route("/guide", defaults={'state': None, 'city': None})
@app.route("/guide/<state>", defaults={'state': None})
@app.route("/guide/<state>/<city>")
def guide_route(state, city):
if state == 'top_100':
return render_template('top_100.html')
elif state:
return render_template('state.html', data={'state': state})
elif state and city:
return render_template('city.html', data={'state': state, 'city': city})
else:
return render_template('something_else.html')
However, when I go to /guide/top_100
or /guide
in my web browser, it redirects me to /guide/None/None
which is a 404. What's also interesting is that I've now put print statements inside every part of the guide_route()
function and none of them fire. So something isn't working in the routing table at all.
How can I get these optional parameters to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您输入默认值的方式有误。您必须在函数定义中执行此操作(而不是在路由中):
https://flask.palletsprojects.com/en/2.0.x/quickstart/#variable-rules。
具有默认值的示例: https://flask.palletsprojects.com /en/2.0.x/quickstart/#rendering-templates
(我还颠倒了两个 elif 条件)
There is a mistake in the way you input the default values. You have to do it in the function definition (and not in routes) :
https://flask.palletsprojects.com/en/2.0.x/quickstart/#variable-rules.
An example with default value : https://flask.palletsprojects.com/en/2.0.x/quickstart/#rendering-templates
(I also inverted two elif conditions)