我是 Api 开发的新手,我一直在关注 YouTube 上的本教程,目前我很擅长使用 FastApi 和 SQL alchemy 执行删除操作。我正在使用邮递员来测试我的 API,每次发送删除请求时,它都会发回 405 错误。我搜索了我的代码,但似乎无法弄清楚问题是什么,任何人都可以帮助我。这是代码示例。
@app.delete("posts/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_posts(id: int,db: Session=Depends(get_db)):
#cur.execute("DELETE FROM posts WHERE id=%s RETURNING * ", (str(id),))
#deleted_post = cur.fetchone()
#conn.commit()
post = db.query(models.Post).filter(models.Post.id==id)
if post.first() == None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"post with {id} not found!")
post.delete(synchronize_session=False)
db.commit()
return Response(status_code=status.HTTP_204_NO_CONTENT)
我搜索了代码,没有发现错误。
您应该从“/”开始路径:
@app.delete("/posts/{id}", status_code=status.HTTP_204_NO_CONTENT)