📜  在烧瓶 sqlalchemy 中按 id 删除记录 - Python (1)

📅  最后修改于: 2023-12-03 15:23:35.201000             🧑  作者: Mango

在烧瓶 SQLAlchemy 中按 id 删除记录 - Python

在使用烧瓶(Bottle)和SQLAlchemy编写Web应用程序时,需要经常进行数据的增、删、改和查操作。本篇文章将介绍如何使用SQLAlchemy在烧瓶中按照id删除数据库中的记录。

代码实现
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from bottle import Bottle, request

Base = declarative_base()
app = Bottle()

class Book(Base):
    __tablename__ = 'book'
    id = Column(Integer, primary_key=True)
    title = Column(String(50), nullable=False)
    author = Column(String(50), nullable=False)
    price = Column(Integer, nullable=False)

engine = create_engine('sqlite:///book.db', echo=True)
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

@app.route('/book/<id:int>', method='DELETE')
def delete_book(id):
    book = session.query(Book).filter_by(id=id).first()
    if book:
        session.delete(book)
        session.commit()
        return {'message': f'Book {id} deleted.'}
    else:
        return {'message': f'Book {id} not found.'}
代码说明
  • 使用SQLAlchemy创建数据库引擎和会话(Session)。
  • 声明一个Book类作为ORM模型,映射到数据库中的book表。
  • delete_book路由中,使用session.query查询数据库中的Book记录,并将查询条件设置为id等于传入参数id的记录。如果找到了记录,则使用session.delete删除该记录,并使用session.commit提交更改。如果未找到记录,则返回“Book {id} not found.”错误消息。
使用方法

在代码中声明了一个delete_book路由,并将其方法设置为DELETE。运行程序时,访问/book/{id}的DELETE请求将触发该路由。

示例:

DELETE http://localhost:8080/book/1

SUCCESS RESPONSE:

{
    "message": "Book 1 deleted."
}

如果id为1的Book记录不存在,则会返回如下错误消息:

{
    "message": "Book 1 not found."
}
总结

本篇文章介绍了如何使用SQLAlchemy在烧瓶中按照id删除数据库中的记录。使用ORM模型可以方便地进行数据库操作,使程序员可以更加专注于业务逻辑的编写。