Python 我是否可以向SQLAlchemy中的模型添加一个在删除该项时触发的事件?
在我的应用程序中,表“文件”中的行可以通过两种方式删除。直接删除,如Python 我是否可以向SQLAlchemy中的模型添加一个在删除该项时触发的事件?,python,sqlalchemy,Python,Sqlalchemy,在我的应用程序中,表“文件”中的行可以通过两种方式删除。直接删除,如session.delete(file),或作为级联删除的结果。当删除行时,我想从文件系统中删除该文件,即数据库行表示的文件。我有办法做到吗 我的模型如下所示: class File(ModelBase): """Model for the 'files' table. This table holds data about uploaded files. """ __tablename__
session.delete(file)
,或作为级联删除的结果。当删除行时,我想从文件系统中删除该文件,即数据库行表示的文件。我有办法做到吗
我的模型如下所示:
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):
# ...
类文件(ModelBase):
“”“文件”表的模型。”。
此表包含有关上载文件的数据。
"""
__tablename_uu='文件'
#纵队
id=列(整数,主键=True)
上传的\u by\u id=列(整数,外键(User.\u tablename\u+'.id'),
可空=假)
path=Column(VARCHAR(255),nullable=False)#服务器上的文件名
name=Column(VARCHAR(255),nullable=False)#原始文件名
mime=列(VARCHAR(75))
size=列(整数,null=False)#文件大小(字节)
上传地址=列(DATETIME,nullable=False)
#关系
上传人=关系('User',backref='files\u upload')
def uuu init uuuu(自我、上传人、路径、名称):
使用ProjectRootContext():
self.upload\u by=上传人
self.path=path
self.name=名称
self.mime=mimetypes.guess\u类型(路径)[0]
self.size=os.path.getsize(路径)
self.upload_at=datetime.now()
定义报告(自我):
返回“”%(repr(self.id)、repr(self.name))
#用于保存上载文件的Factory功能
@类方法
来自现场存储的def(cls、上传人、现场存储):
# ...
您试过了吗