mirror of
https://gitlab.ub.uni-bielefeld.de/sfb1288inf/nopaque.git
synced 2024-12-25 19:04:18 +00:00
41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
from datetime import datetime
|
|
from flask import current_app
|
|
from werkzeug.utils import secure_filename
|
|
from app import db
|
|
|
|
|
|
class FileMixin:
|
|
'''
|
|
Mixin for db.Model classes. All file related models should use this.
|
|
'''
|
|
creation_date = db.Column(db.DateTime, default=datetime.utcnow)
|
|
filename = db.Column(db.String(255))
|
|
mimetype = db.Column(db.String(255))
|
|
|
|
def file_mixin_to_json_serializeable(self, backrefs=False, relationships=False):
|
|
return {
|
|
'creation_date': f'{self.creation_date.isoformat()}Z',
|
|
'filename': self.filename,
|
|
'mimetype': self.mimetype
|
|
}
|
|
|
|
@classmethod
|
|
def create(cls, file_storage, **kwargs):
|
|
filename = kwargs.pop('filename', file_storage.filename)
|
|
mimetype = kwargs.pop('mimetype', file_storage.mimetype)
|
|
obj = cls(
|
|
filename=secure_filename(filename),
|
|
mimetype=mimetype,
|
|
**kwargs
|
|
)
|
|
db.session.add(obj)
|
|
db.session.flush(objects=[obj])
|
|
db.session.refresh(obj)
|
|
try:
|
|
file_storage.save(obj.path)
|
|
except (AttributeError, OSError) as e:
|
|
current_app.logger.error(e)
|
|
db.session.rollback()
|
|
raise e
|
|
return obj
|