我可以将事件添加到SQLAlchemy中的模型中,该模型在删除项目时触发?
问题描述:
在我的应用程序中,可以通过两种方式删除表“文件”中的行。直接,如session.delete(file)
或作为级联删除的结果。我想从我的文件系统中删除该文件,这是数据库行代表的文件,当该行被删除时。有什么办法可以做到吗?我可以将事件添加到SQLAlchemy中的模型中,该模型在删除项目时触发?
我的模型看起来是这样的:
class File(ModelBase):
"""Model for the 'files' table.
This table holds data about uploaded files.
"""
__tablename__ = 'files'
# Columns
id = Column(INTEGER, primary_key=True)
uploaded_by_id = Column(INTEGER, ForeignKey(User.__tablename__ + '.id'),
nullable=False)
path = Column(VARCHAR(255), nullable=False) # The file's name on the server
name = Column(VARCHAR(255), nullable=False) # The original file name
mime = Column(VARCHAR(75))
size = Column(INTEGER, nullable=False) # File size in bytes
uploaded_at = Column(DATETIME, nullable=False)
# Relationships
uploaded_by = relationship('User', backref='files_uploaded')
def __init__(self, uploaded_by, path, name):
with ProjectRootContext():
self.uploaded_by = uploaded_by
self.path = path
self.name = name
self.mime = mimetypes.guess_type(path)[0]
self.size = os.path.getsize(path)
self.uploaded_at = datetime.now()
def __repr__(self):
return '<File(id=%s,name=%s)>' % (repr(self.id), repr(self.name))
# Factory function for saving an uploaded file
@classmethod
def from_fieldstorage(cls, uploaded_by, fieldstorage):
# ...