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

如何使用Flask+SQL Server删除记录,解决Method Not Allowed报错

问题原因

浏览器点击<a>标签默认发起的是GET请求,但你代码中/delete/<id>路由仅配置了允许DELETE方法,请求与路由规则不匹配,因此抛出405方法不允许错误。

解决办法

方案1:快速适配(适合小型内部项目)

直接修改路由的允许方法列表,新增GET支持即可,同时可删除路由内部多余的请求方法判断:
修改api2.py中的删除路由代码:

@app.route('/delete/<string:id>', methods=['GET', 'DELETE'])
def delete(id):
    cursor=conn.cursor()
    # 注意单元素参数要加逗号,否则会被识别为字符串而非元组
    cursor.execute("DELETE FROM notes WHERE id=?", (id,))
    conn.commit()
    cursor.close()
    flash("记录删除成功")
    return redirect('/')

修改完成后直接点击删除链接即可正常触发删除逻辑。

方案2:规范实现(符合HTTP规范,避免误删)

GET请求的设计初衷是查询数据,不应该用来执行数据修改操作,否则可能出现爬虫爬取链接误删数据的问题。更规范的实现方式是用表单发起POST请求:

  1. 修改home.html中的删除按钮代码:
<td> 
  <a href='/edit/{{note[0]}}'>Edit</a> 
  <a href='/new_item'>Add</a> 
  <form action="/delete/{{note[0]}}" method="post" style="display:inline;">
    <button type="submit" style="background:none;border:none;color:blue;text-decoration:underline;cursor:pointer;">Delete</button>
  </form>
</td>
  1. 修改api2.py中的删除路由配置:
@app.route('/delete/<string:id>', methods=['POST', 'DELETE'])
def delete(id):
    cursor=conn.cursor()
    cursor.execute("DELETE FROM notes WHERE id=?", (id,))
    conn.commit()
    cursor.close()
    flash("记录删除成功")
    return redirect('/')

内容的提问来源于stack exchange,提问作者BI Dude

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:18:00