Reputation: 59363
In my application, rows in the table "files" can be deleted in two ways. Either directly, like session.delete(file)
or as the result of a cascade delete. I would like to delete the file from my file system, the file that the database row represents, when the row is deleted. Is there any way I can do that?
My model looks like this:
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):
# ...
Upvotes: 2
Views: 177