Flask开发场景下如何为同目录多导航项配置正确的页面路由
Flask 旅游网站城市页面路由配置修正方案
现有代码的问题点
- 路由语法不匹配 Flask 规范:Flask 动态路径参数使用
<参数名>格式定义,原代码写的/destinations/{id}是其他框架的语法,会直接导致路由注册失败 - 缺失核心初始化代码:原 demo.py 没有创建 Flask 应用实例,
@app.route装饰器没有可绑定的应用对象,服务根本无法启动 - 导航硬编码相对路径:写死的
destinations/xxx相对路径,会随当前页面所在的层级动态拼接,极易出现跳转路径错误 - 缺少异常容错:如果用户输入不存在的城市标识,没有对应模板时会抛出未捕获的系统异常,体验较差
修正后的完整实现
1. 后端路由代码(demo.py)
from flask import Flask, render_template, abort # 初始化Flask应用实例 app = Flask(__name__) # 正确定义动态路由 @app.route('/destinations/<city_id>', methods=['GET']) def destinations(city_id): # 拼接对应城市的模板路径 target_template = f"destinations/{city_id}.html" try: return render_template(target_template) except: # 模板不存在时返回标准404响应 abort(404) if __name__ == "__main__": app.run(debug=True)
2. 前端导航代码优化
替换硬编码的href为Flask模板内置的url_for方法生成的绝对路径,从根源避免路径错位:
<li><a href="#">Destinations</a> <ul class="nav-dropdown"> <li><a href="{{ url_for('destinations', city_id='london') }}">London</a></li> <li><a href="{{ url_for('destinations', city_id='paris') }}">Paris</a></li> <li><a href="{{ url_for('destinations', city_id='newyork') }}">New York</a></li> <li><a href="{{ url_for('destinations', city_id='moscow') }}">Moscow</a></li> <li><a href="{{ url_for('destinations', city_id='vegas') }}">Las Vegas</a></li> <li><a href="{{ url_for('destinations', city_id='pataya') }}">Pataya</a></li> </ul> </li>
注意:请确保所有城市HTML模板都存放在项目的templates/destinations/目录下,和代码中拼接的路径保持一致。
内容的提问来源于stack exchange,提问作者Malith Senanayake
相关产品推荐
相关产品推荐

