diff options
-rw-r--r-- | db.py | 19 |
1 files changed, 16 insertions, 3 deletions
@@ -4,7 +4,7 @@ from sqlalchemy.orm import sessionmaker, relation, backref from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.exc import IntegrityError from sqlalchemy.sql import and_ -import settings +import settings, os engine = create_engine(settings.db_path) @@ -39,9 +39,22 @@ class File(Base): self.date = date self.user_id = user_id + @staticmethod + def pretty_size(size): + suffixes = (('B', 2**10), ('KiB', 2**20), ('MiB', 2**30), ('GiB', 2**40), ('TiB', 2**50)) + for suf, lim in suffixes: + if size > lim: + continue + else: + return '%s %s' % (str(round(size/float(lim/2**10), 2)), suf) + + def get_path(self): + return os.path.join(settings.file_directory, self.hash + os.path.splitext(self.filename)[1]) + def html(self): - return '<a href="/f/{hash}/{filename}">{filename}</a> on {date}'.format( - hash = self.hash, filename = self.filename, date = self.date.strftime('%Y-%m-%d %H:%M:%S UTC')) + return '<a href="/f/{hash}/{filename}">{filename}</a> <sup><a href="/f/{hash}">1</a> <a href="/f/{hash}{ext}">2</a></sup> ({size}) on {date}'.format( + hash = self.hash, filename = self.filename, ext = os.path.splitext(self.filename)[1], + size = self.pretty_size(os.path.getsize(self.get_path())), date = self.date.strftime('%Y-%m-%d %H:%M:%S UTC')) Base.metadata.create_all() Session = sessionmaker(bind = engine, autoflush = True, autocommit = False) |