I need to create custom sqlalchemy type which would receive path to the file and while saving the object it would move the file to the special place which contains in its path the name of the field, the name of the table and the id of the curent record.
Something like this:
root = pathlib.Path('/path/to/files/')
class SpecialFileType(TypeDecorator):
impl = String
def process_bind_param(self, value, dialect):
path = pathlib.Path(value)
new_path = root / self.table_name / str(self.current_record_id) / self.field_name / path.name
# Of course there is no self.table_name, self.current_record_id, self.field_name and that is the problem.
# Yes, I can e. g. submit table_name and field_name in __init__ and remember them which is ugly but would work
# (but still I would like to get them somehow automatically, without explicitly specifying them each time declaring this field).
# But how can I get the id of the current record here?
path.replace(new_path)
return path.name
def process_result_value(self, value, dialect):
new_path = root / self.table_name / str(self.record_id) / self.field_name / value
return new_path
class MyModel(Base):
id = Column(Integer, primary_key=True)
file = Column(SpecialFileType)
Maybe it is possible to achieve the same effect with listening to model events? But then there should be a way to automatically bind listening to all the models containing this special field. Maybe subclassing the Base class or something like this?