PCv5/app/models/attachment.py

51 lines
1.3 KiB
Python

from werkzeug.utils import secure_filename
from sqlalchemy.orm import backref
from app import db
from app.utils.filesize import filesize
from config import V5Config
import os
class Attachment(db.Model):
__tablename__ = 'attachment'
id = db.Column(db.Integer, primary_key=True)
# Original name of the file
name = db.Column(db.Unicode(64))
# The comment linked with
comment_id = db.Column(db.Integer, db.ForeignKey('comment.id'), nullable=False)
comment = db.relationship('Comment', backref=backref('attachments'))
# The size of the file
size = db.Column(db.Integer)
# Storage file path
@property
def path(self):
return os.path.join(V5Config.DATA_FOLDER, "attachments",
f"{self.id:05}", self.name)
@property
def url(self):
return f"/fichiers/{self.id:05}/{self.name}"
def __init__(self, file, comment):
self.name = secure_filename(file.filename)
self.size = filesize(file)
self.comment = comment
def set_file(self, file):
os.mkdir(os.path.dirname(self.path))
file.save(self.path)
def edit_file(self, file):
file.name = secure_filename(file.filename)
self.set_file(file)
def delete_file(self):
try:
os.delete(self.path)
except FileNotFoundError:
pass