class Country(db.Model, BaseModelMixin): __tablename__ = 'countries' country_id = db.Column(db.Integer, primary_key=True) iso = db.Column(db.String(2), nullable=False) name = db.Column(db.String(45), nullable=False) spanish_name = db.Column(db.String(45), nullable=False) users = db.relationship('User', back_populates='country', cascade='all, delete, delete-orphan', passive_deletes=True)
class Categorias(db.Model, BaseModelMixin): __tablename__ = "CATEGORIAS" idCategoria = db.Column(db.Integer, primary_key=True) nombreCategoria = db.Column(db.String) fechaCreacion = db.Column(db.Date) sub_categorias = db.relationship('Sub_Categorias', backref='Categorias', lazy=True)
class Product(db.Model): __tablename__ = 'products' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) price = db.Column(db.Float(precision=2)) quantity = db.Column(db.Integer()) description = db.Column(db.String(200)) minutes_preparation = db.Column(db.Integer()) image_path = db.Column(db.String(80)) product_type_id = db.Column(db.Integer, db.ForeignKey('product_types.id')) product_type = db.relationship('ProductType') #orders = db.relationship('Order', lazy='dynamic') def __init__(self, product_type_id, name, price, quantity, description, minutes_preparation,image_path): self.name = name self.price = price self.quantity = quantity self.description = description self.minutes_preparation = minutes_preparation self.image_path=image_path self.product_type_id=product_type_id @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first() @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).first() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit() @classmethod def init_data(cls): cls(1, "Hamburger", 6, 10, "A 150Gr grilled meat hamburger. Comes with french fries and salad.", 15, "/images/hamburger.jpg").save_to_db() cls(1, "Chicken", 7, 10, "A 300Gr breaded chicken. comes with potatoes and salad", 15, "/images/chicken.jpg").save_to_db() cls(1, "Paella", 9, 10, "Perfect for the seafood lovers, it comes with oysters and mussels", 15, "/images/paella.jpg").save_to_db() cls(1, "Ribs", 12, 10, "300Gr Ribs. Comes with french fries.", 15, "/images/ribs.jpg").save_to_db() cls(1, "Salmon", 12, 10, "Chilean salmon. Comes with vegetables.", 15, "/images/salmon.jpg").save_to_db() cls(1, "Wrap", 7, 10, "Wrap with chicken and salad.", 15, "/images/wrap.jpg").save_to_db() cls(2, "Soda", 2, 7, "250cc soda. The soda comes with pieces of fruit.", 5, "/images/soda.jpg").save_to_db() cls(2, "Juice", 3, 7, "330cc juice. Made of tropical fruits.", 9, "/images/juice.jpg").save_to_db() cls(2, "Tee", 3, 7, "200cc Tee.", 12, "/images/tee.jpg").save_to_db() cls(2, "Beer", 2, 7, "500cc Beer.", 3, "/images/beer.jpg").save_to_db() cls(3, "Pancakes", 4, 7, "Baked pancakes with syrup or honey.", 12, "/images/pancakes.jpg").save_to_db() cls(3, "Macaroons", 3, 7, "Try our special macaroon recipe.", 3, "/images/macaroons.jpg").save_to_db() cls(3, "Forest fruit Cake", 3, 7, "This cake has a great variety of forest fruits, such as blackberries and raspberries.", 5, "/images/cake.jpg").save_to_db()
class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) #account_types = Personal, Professional, Business, Premium account_type = db.Column(db.String(120), default='Business') user_type = db.Column(db.String(120), default='Beta') state = db.Column(db.String(120), default=fake.state_abbr()) country = db.Column(db.String(120), default=fake.country_code(representation="alpha-2")) set_path = db.Column(db.String(120), default='default') company = db.Column(db.String(255), default=fake.company()) plan_id = db.Column(db.Integer, db.ForeignKey('plan.id'), default=1) plan = db.relationship("Plan", backref="user", lazy="subquery") def _set_default_plan(self): return Plan.query.filter_by(name='free').first() def __repr__(self): return '<User {}>'.format(self.username) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) def get_email_hash(self): return hashlib.md5(self.email.encode()).hexdigest() def get_ld_user(self): app_version = current_app.config['VERSION'] milliseconds = int(round(time.time() * 1000)) user_key = self.get_email_hash() user = { 'key': user_key, 'email': self.email, "custom": { 'account_type': self.account_type, 'user_type': self.user_type, 'state': self.state, 'country': self.country, 'app_version': app_version, 'company': self.company or 'None', 'date': milliseconds, 'plan': self.plan.name }, 'privateAttributeNames': ['account_type', 'state'], } return user def get_random_ld_user(self): user = {'key': str(uuid.uuid1()), 'anonymous': True} return user
class Usuarios(db.Model, BaseModelMixin): __tablename__ = "USUARIOS" idUsuario = db.Column(db.Integer, primary_key=True) nombreUsuario = db.Column(db.String) apellidoPatUsuario = db.Column(db.String) apellidoMatUsuario = db.Column(db.String) idRol = db.Column(db.Integer, db.ForeignKey(Rol.idRol), nullable=False) Ruc = db.Column(db.String) razonSocial = db.Column(db.String) nombreComercial = db.Column(db.String) codigoPostalPais = db.Column(db.String) telefono = db.Column(db.String) celular = db.Column(db.String) email = db.Column(db.String) password = db.Column(db.String) imagen = db.Column(db.String) subastas = db.relationship('Subastas', backref='Usuarios', lazy=True) pujas = db.relationship('Pujas', backref='Usuarios', lazy=True)
class TestCase(db.Model): __tablename__ = 'testcases' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), index=True, unique=True) type_id = db.Column(db.Integer, db.ForeignKey('testtypes.id')) type = db.relationship( 'TestType', backref=db.backref('testcases', lazy='dynamic'), ) category_id = db.Column(db.Integer, db.ForeignKey('categories.id')) category = db.relationship( 'Category', backref=db.backref('testcases', lazy='dynamic'), ) def __repr__(self): return '<Test Case {0}>'.format(self.name)
class Supermercados(db.Model, BaseModelMixin): __tablename__ = "SUPERMERCADOS" idSupermercado = db.Column(db.Integer, primary_key=True) nombreSupermercado = db.Column(db.String) imagenSupermercado = db.Column(db.String) urlSupermercado = db.Column(db.String) productos_supermercados = db.relationship('Productos_Supermercados', backref='Supermercados', lazy=True)
class Rol(db.Model, BaseModelMixin): __tablename__ = "ROL" idRol = db.Column(db.Integer, primary_key=True) nombreRol = db.Column(db.String) usuarios = db.relationship('Usuarios', backref='Rol', lazy=True) def __init__(self, idRol, nombreRol): self.idRol = idRol self.nombreRol = nombreRol
class UserModel(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255)) password = db.Column(db.String(60)) right_id = db.Column(db.Integer, db.ForeignKey('rights.id'), default=1) right = db.relationship('UserRightModel', back_populates="users") username = db.Column(db.String(100), default='') position = db.Column(db.String(100), default='') hide = db.Column(db.Boolean(), default=0) @validates('email') def validate_email(self, key, email): assert '@' in email return email def __init__(self, email, password): self.email = email self.password = password def json(self): right = UserRightModel.find_by_id(self.right_id) return { 'id': self.id, 'email': self.email, 'right_id': self.right_id, 'right': self.right.json(), 'username': self.username, 'position': self.position, 'hide': self.hide } @classmethod def find_by_email(cls, email): return cls.query.filter_by(email=email).first() @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first() @classmethod def find_all(cls): return cls.query.all() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit() @classmethod def create_random_password(cls): return secrets.tocken_hex(8)
class Municipio(db.Model): __tablename__ = 'municipio' id = db.Column(db.Integer, primary_key=True) nombre = db.Column(db.String, unique=True) centros_en_este_municipio = db.relationship("Centro_de_ayuda", back_populates="municipio") fase_id = db.Column(db.Integer) def all(): return Municipio.query.all()
class Estado_centro(db.Model): __tablename__ = 'estado_centro' id = db.Column(db.Integer, primary_key=True) nombre = db.Column(db.String, unique=True) centros_en_este_estado = db.relationship("Centro_de_ayuda", back_populates="estado") def all(): return Estado_centro.query.all() ######################## ESTADO ########################
class Aplicativo(db.Model): __tablename__ = 'aplicativos' id = db.Column(db.Integer, primary_key=True) codigo = db.Column(db.String) nome = db.Column(db.String) valor = db.Column(db.Integer) assinatura = db.relationship('Assinatura', secondary='assinatura_aplicativo')
class ProductTransaction(db.Model): __tablename__ = 'product_transaction' id = db.Column( db.Integer, primary_key = True, autoincrement = True ) product_id = db.Column( db.Integer, db.ForeignKey('products.id'), nullable = False ) transaction_id = db.Column( db.Integer, db.ForeignKey('transactions.id'), nullable = False ) product_qty = db.Column( db.Integer, nullable = False ) product = db.relationship( 'Product', backref = 'product_assoc', lazy = 'joined' ) transaction = db.relationship( 'Transaction', backref = 'transaction_assoc' 'lazy' = 'joined' ) @event.listens_for(db.session, 'before_flush') def reduceProductStock(*args): sess = args[0] for obj in sess.new: if not isinstance(obj, ProductTransactions): continue product = Products.query.filter_by(id = obj.product_id).first() product.stock_qty = product.stock_qty - obj.product_qty db.session.add(product)
class Tipos_Productos(db.Model, BaseModelMixin): __tablename__ = "TIPOS_PRODUCTOS" idTipoProducto = db.Column(db.Integer, primary_key=True) nombreProducto = db.Column(db.String) idSubCategorias = db.Column(db.Integer, db.ForeignKey(Sub_Categorias.idSubCategorias), nullable=False) productos = db.relationship('Productos', backref='Tipos_Productos', lazy=True)
class Estado(db.Model, BaseModelMixin): __tablename__ = "ESTADO" idEstado = db.Column(db.Integer, primary_key=True) nombreEstado = db.Column(db.String) codEstado = db.Column(db.String) subastas = db.relationship('Subastas', backref='Estado', lazy=True) @classmethod def find_by_cod(cls, cod): return cls.query.filter_by(codEstado=cod).first()
class Order(db.Model): id = db.Column(db.Integer, primary_key=True) date = db.Column(db.DateTime, nullable=False) address = db.Column(db.String(255), nullable=False) customer_id = db.Column(db.String(255), db.ForeignKey('customer.id'), nullable=False) customer = db.relationship('Customer', backref=db.backref('orders', lazy=True))
class ScheduleModel(db.Model): """ Modelo que armazena toda a programação do evento como: palestras, minicursos e outros eventos personalizados. """ __tablename__ = 'programacao' id = db.Column(db.Integer, primary_key=True) local = db.Column(db.String, nullable=False) dia = db.Column(db.Integer, nullable=False) data_inicio = db.Column(db.DateTime, nullable=False) data_fim = db.Column(db.DateTime, nullable=False) # Courses vagas = db.Column(db.Integer, default=None) turma = db.Column(db.String, default=None) course_id = db.Column(db.Integer, db.ForeignKey('minicurso.id')) # Lecture lecture_id = db.Column(db.Integer, db.ForeignKey('palestra.id')) # Other titulo = db.Column(db.String, default=None) descricao = db.Column(db.String, default=None) lecture = db.relationship('LectureModel', uselist=False) course = db.relationship('CourseModel', uselist=False) def vacRemaining(self): reserved = CourseSubsModel.query.filter(or_( CourseSubsModel.option1 == self.id, CourseSubsModel.option2 == self.id )).count() return self.vagas - reserved def setCourse(self, vagas, turma, course): self.vagas = vagas self.turma = turma self.course = course def setLecture(self, lecture): self.lecture = lecture def setOther(self, titulo, descricao): self.titulo = titulo self.descricao = descricao
class Direcciones(db.Model, BaseModelMixin): __tablename__ = "DIRECCIONES" idDireccion = db.Column(db.Integer, primary_key=True) idUsuario = db.Column(db.Integer, db.ForeignKey(Usuarios.idUsuario), nullable=False) direccion = db.Column(db.String) latitud = db.Column(db.String) longitud = db.Column(db.String) subastas = db.relationship('Subastas', backref='Direcciones', lazy=True)
class Sub_Categorias(db.Model, BaseModelMixin): __tablename__ = "SUB_CATEGORIAS" idSubCategorias = db.Column(db.Integer, primary_key=True) nombreSubCategoria = db.Column(db.String) idCategoria = db.Column(db.Integer, db.ForeignKey(Categorias.idCategoria), nullable=False) categoria = db.relationship('Tipos_Productos', backref='Sub_Categorias', lazy=True)
class Category(db.Model): __tablename__ = 'categories' id = db.Column( db.Integer, primary_key = True, autoincrement = True ) parent_id = db.Column( db.Integer, db.ForeignKey('categories.id') ) description = db.Column( db.Text ) slug = db.Column( db.String(100), nullable = False ) identifier_code = db.Column( db.String(3), nullable = False ) children = db.relationship( "Category", backref = backref('parent', remote_side=[id]), lazy = 'joined', join_depth = 2 ) products = db.relationship( 'Product', secondary = category_product_table, backref = 'categories', lazy = 'joined' ) def __init__(self, *args, **kwargs): if not in kwargs: self.slug = slugify(kwargs['name']) self.identifier_code = kwargs['name'][0:2].lower() super().__init__(*args, **kwargs)
class Author(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(60), nullable=False) surname = db.Column(db.String(60), nullable=False) email = db.Column(db.String(120), nullable=False) description = db.Column(db.String(500), nullable=True) technologies = db.relationship('Technology', secondary='author_technology', lazy=False, backref=db.backref('authors', lazy=True)) projects = db.relationship('Project', backref='author', lazy=True) def is_valid(self): for technology in self.technologies: if technology is None: return False return self.name != '' and self.surname != '' and self.email != '' def format(self): technologies = [tech.format() for tech in self.technologies] return { 'id': self.id, 'name': self.name, 'surname': self.surname, 'email': self.email, 'description': self.description, 'technologies': technologies, } def insert(self): db.session.add(self) db.session.commit() def update(self): db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def __repr__(self): return f'''
class RecordCalled(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) type_called_id = db.Column(db.Integer, db.ForeignKey(TypeCalled.id), nullable=False) country_id = db.Column(db.Integer, db.ForeignKey(Country.id), nullable=False) reason_id = db.Column(db.Integer, db.ForeignKey(Reason.id), nullable=False) text = db.Column(db.Text, nullable=False) # relationships type = db.relationship("TypeCalled", foreign_keys=[type_called_id]) country = db.relationship("Country", foreign_keys=[country_id]) reason = db.relationship("Reason", foreign_keys=[reason_id]) created_date = db.Column(db.DateTime, default=datetime.now()) update_date = db.Column(db.DateTime, default=datetime.now(), onupdate=datetime.now())
class Type(Base): name = db.Column(db.String(144), nullable=False) observatory_id = db.Column(db.Integer, db.ForeignKey('observatory.id'), nullable=False) Observationperiod = db.relationship("Observationperiod", backref="type", lazy=True) def __init__ (self, name, observatory_id): self.name=name self.observatory_id=observatory_id
class WeekData(db.Model): __tablename__ = 'week_data' id = db.Column(db.Integer, primary_key=True) donations = db.Column(db.Integer) crowns = db.Column(db.Integer) year = db.Column(db.Integer) week = db.Column(db.Integer) clan_player = db.relationship('ClanPlayer', backref='data') clan_player_id = db.Column(db.Integer, db.ForeignKey('clan_player.id'))
class Productos(db.Model, BaseModelMixin): __tablename__ = "PRODUCTOS" idProducto = db.Column(db.Integer, primary_key=True) idTipoProducto = db.Column(db.Integer, db.ForeignKey(Tipos_Productos.idTipoProducto), nullable=False) nombreProducto = db.Column(db.String) contenidoProducto = db.Column(db.String) Imagen = db.Column(db.String) codProducto = db.Column(db.String) marca = db.Column(db.String) presentacion = db.Column(db.String) unidadMedida = db.Column(db.String) cantidadPaquete = db.Column(db.Integer) subastas_productos = db.relationship('Subastas_Productos', backref='Productos', lazy=True) productos = db.relationship('Productos_Supermercados', backref='Productos', lazy=True)
class Artist(db.Model, BaseModelMixin): __tablename__ = 'artists' artist_id = db.Column(db.Integer, primary_key=True) spt_artist_id = db.Column(db.String(30), nullable=False, unique=True) artist_name = db.Column(db.String(50), nullable=False) cover_image_url = db.Column(db.String(100)) created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) active = db.Column(db.Integer, default=1) albums = db.relationship('Album', back_populates='artists', secondary=albums_artists, passive_deletes=True)
class Productos(db.Model): __tablename__ = "PRODUCTOS" idProducto = db.Column(db.Integer, primary_key=True) idCategoria = db.Column(db.Integer, db.ForeignKey(Categorias.idCategoria), nullable=False) nombreProducto = db.Column(db.String) contenidoProducto = db.Column(db.String) subastas_productos = db.relationship('Subastas_Productos', backref='Productos', lazy=True)
class SubjectModel(db.Model): __tablename__ = 'disciplina' """ Modelo que armazena todas disciplinas cadastradas pelos usuarios. """ id = db.Column(db.Integer, primary_key=True) sub_name = db.Column(db.String, nullable=False) sub_group = db.Column(db.String, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('usuario.id')) user_associated = db.relationship('SubuserModel', backref='subj_associate', passive_deletes=True) presence_count = db.relationship('PresenceModel', backref='subject_info', passive_deletes=True) def __init__(self, sub_name, sub_group, creator): self.sub_name = sub_name self.sub_group = sub_group self.creator = creator
class Options(db.Model): """ Model for options """ __tablename__ = "options" id = db.Column(db.Integer, primary_key = True) choice = db.Column(db.String(200)) question_id = db.Column(db.Integer, db.ForeignKey('question.id')) votes = db.relationship('Vote', backref='options', lazy='dynamic') def __repr__(self): return f'{self.id}, {self.choice},{self.question_id}, {self.votes}'
class Solve(db.Model): __table_args__ = ({'mysql_character_set': 'utf8mb4', 'mysql_collate': 'utf8mb4_unicode_520_ci'}) id = Column('id', Integer, primary_key=True) user_id = Column('user', Integer, ForeignKey('user.id'), nullable=False) user = db.relationship('User', backref=db.backref('solves', lazy=True)) challenge_id = Column('challenge', Integer, ForeignKey('challenge.id'), nullable=False) challenge = db.relationship('Challenge', backref=db.backref('solves', lazy=True)) timestamp = Column('created', DateTime, nullable=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs, timestamp=datetime.utcnow()) def jsonify(self): # TODO check points (DownloadPizza reported that the points on account page are not correct) return { 'challenge': self.challenge.min_jsonify(), 'timestamp': self.timestamp }