You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask项目中配置实现主页面index.html到candidates.html的跳转

如何在Flask项目中配置实现主页面index.html到candidates.html的跳转

嘿,我来帮你搞定这个跳转问题!首先得明确:Flask里每个页面都需要对应的路由函数来处理请求,你现在的app.py里只配置了主页面/的路由,直接在index里加链接自然找不到candidates.html,咱们一步步来解决:

1. 给候选人页面添加路由

在你的app.py里,添加一个专门处理候选人页面请求的路由函数,就像主页面那样:

@app.route('/candidates')
def candidates():
    # 确保你的candidates.html放在Flask默认的templates文件夹里
    return render_template('candidates.html')

这样当用户访问/candidates路径时,Flask就会返回对应的模板页面了。

2. 在主页面index.html里添加正确的跳转链接

别直接写死链接地址,用Flask的url_for()函数来生成路由对应的URL,这样哪怕以后你改了路由路径,链接也能自动生效。在index.html里加这段代码:

<a href="{{ url_for('candidates') }}">跳转到候选人页面</a>

这里的'candidates'要和你刚才在app.py里定义的路由函数名完全一致哦。

额外的重要提醒:修复你的SQL注入风险

哦对了,我注意到你插入数据的时候用了字符串格式化拼接SQL语句,这可是高危的SQL注入漏洞!赶紧改成参数化查询的方式,既安全又规范:

# 把原来的query1和execute改成这样
cursor.execute("INSERT INTO voters (votername,voterage,candidateid) VALUES (?,?,?)", 
               (votername, voterage, candidateid))

用?作为占位符,把参数单独传给execute()方法,Flask会自动帮你处理转义,彻底避免注入问题。

现在重启你的Flask服务,点击主页面的链接就能正常跳转到候选人页面啦!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 03:08:26