from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text, Index, ForeignKey from sqlalchemy.ext.declarative import declarative_base 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 engine = create_engine(settings.db_path) Base = declarative_base(bind = engine) class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key = True) username = Column(String, unique = True, index = True) password = Column(String) files = relation('File', backref = 'user', order_by = 'File.date.desc()') def __init__(self, username, password): self.username = username self.password = password class File(Base): __tablename__ = 'files' id = Column(Integer, primary_key = True) hash = Column(String, unique = True, index = True) filename = Column(String) date = Column(DateTime) user_id = Column(Integer, ForeignKey('users.id'), nullable = True) def __init__(self, hash, filename, date, user_id = None): self.hash = hash self.filename = filename self.date = date self.user_id = user_id def html(self): return '{filename} on {date}'.format( hash = self.hash, filename = self.filename, date = self.date.strftime('%Y-%m-%d %H:%M:%S UTC')) Base.metadata.create_all() Session = sessionmaker(bind = engine, autoflush = True, autocommit = False)