class Stock(db.Model): id = db.Column(db.Integer, primary_key=True) product_id = db.Column(db.Integer, db.ForeignKey('product.id')) quantity = db.Column(db.Integer, nullable=False) created_at = db.Column(db.DateTime, default=datetime.now()) updated_at = db.Column(db.DateTime, default=datetime.now())
from sqlalchemy import Column, Integer, ForeignKey from sqlalchemy.ext.declarative import declarative_base from typing import Text from app.db import db Base = declarative_base() articles_keywords = db.Table( 'article_keyword', db.Column('article_id', db.Integer, db.ForeignKey('articles.id', ondelete='CASCADE'), nullable=False), db.Column('keyword_id', db.Integer, db.ForeignKey('keywords.id', ondelete='CASCADE'), nullable=False)) class Article(db.Model): __tablename__ = 'articles' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), nullable=False) source = db.Column(db.String(255), nullable=False) date = db.Column(db.DateTime, nullable=False) url = db.Column(db.String(255), nullable=False) author = Column(Integer, ForeignKey("authors.id")) sentences_count = db.Column(db.Integer)
class Turno(db.Model): __tablename__ = 'turnos_para_centro' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String) telefono = db.Column(db.String) nombre = db.Column(db.String) apellido = db.Column(db.String) hora_ini = db.Column(db.String) hora_fin = db.Column(db.String) dia = db.Column(db.String) borrado = db.Column(db.Integer) centro_id = db.Column(db.Integer) disponible = db.Column(db.Integer) def all(): return Turno.query.all() def create(hi, hf, di, ce): em = "" te = "" act = 1 disponible = 1 nuevo_turno = Turno(email=em, telefono=te, hora_ini=hi, hora_fin=hf, dia=di, borrado=act, centro_id=ce, disponible=disponible, nombre="sin nombre", apellido="sin apellido") db.session.add(nuevo_turno) db.session.commit() return True def create_reserva(i, em, te, ce): datos = Turno.query.filter_by(centro_id=ce).first() datos.email = em datos.telefono = te datos.borrado = 1 datos.disponible = 0 db.session.commit() return datos def get_by_id(id): return Turno.query.get(id) def select_turno(centro_id): return Turno.query.filter_by(centro_id=centro_id).all() def select_centro(ide): return Turno.query.filter_by(id=ide).all() def edit(i, em, te, disponible): datos = Turno.query.filter_by(id=i).first() datos.email = em datos.telefono = te datos.borrado = 1 datos.disponible = disponible db.session.commit() return datos def delete(idx): turno = Turno.query.filter_by(id=idx).first() turno.email = '' turno.telefono = '' turno.disponible = 1 db.session.commit() return True def reservar_turno(centro_id, email_donante, nombre_donante, apellido_donante, telefono_donante, hora_inicio, hora_fin, fecha): turno = Turno.query.filter_by(centro_id=centro_id).filter_by( hora_ini=hora_inicio).filter_by(dia=fecha).first() if turno and turno.disponible: turno.email = email_donante turno.telefono = telefono_donante turno.nombre = nombre_donante turno.apellido = apellido_donante turno.disponible = 0 db.session.commit() return True else: # Mod turnos - 07 February 2021 (Sunday) if turno: return False nuevo_turno = Turno(email=email_donante, telefono=telefono_donante, hora_ini=hora_inicio, hora_fin=hora_fin, dia=fecha, borrado=0, centro_id=centro_id, disponible=0, nombre=nombre_donante, apellido=apellido_donante) db.session.add(nuevo_turno) db.session.commit() # /Mod turnos return True def es_valido(centro_id, hora_inicio, fecha): turno = Turno.query.filter_by(centro_id=centro_id).filter_by( hora_ini=hora_inicio).filter_by(dia=fecha).filter_by( disponible=0).first() if turno: print("Se intento reservar un turno ocupado") return False else: return True def ultimos_turnos_para_centro(centro_id): turnos = Turno.query.filter_by(centro_id=centro_id).filter_by( dia >= '1985-01-17').filter_by(disponible=0).all() return turnos def turnos_tomados_del_mes(): # Tenemos que arreglar esta funcion en caso que se modifique el sistema de turnos # Ademas mejorarla para que devuelva solo los turnos del mes # fecha_hace_30_dias = datetime.now() - timedelta(days=30) # fecha_hace_30_dias = fecha_hace_30_dias.strftime("%m-%d-%Y") return Turno.query.filter_by(disponible=0).all() def turnos_tomados_para_centro(id_centro): return Turno.query.filter_by(centro_id=id_centro).filter_by( disponible=0).all() def get_proximos_turnos(centro_id): """ Devuelve un objeto paginable con los turnos de un centro para hoy y los proximos 2 dias """ fecha_hoy = datetime.now().strftime("%Y-%m-%d") fecha_fin = (datetime.now() + timedelta(days=2)).strftime("%Y-%m-%d") return Turno.query.filter_by(centro_id=centro_id).filter( Turno.dia >= fecha_hoy).filter(Turno.dia <= fecha_fin).filter_by( disponible=0) def reservar(centro_id, email_donante, telefono_donante, hora_inicio, hora_fin, fecha): """ Se encarga de reservar el turno, en caso de no ser posible devuelve false """ turno = Turno.query.filter_by(centro_id=centro_id).filter_by( hora_ini=hora_inicio).filter_by(dia=fecha).filter_by( disponible=0).first() if turno == None: return False nueva_reserva = Turno(email=email_donante, telefono=telefono_donante, hora_ini=hora_inicio, hora_fin=hora_fin, dia=fecha, borrado=0, centro_id=centro_id, disponible=0, nombre="sin nombre", apellido="sin apellido") db.session.add(nueva_reserva) db.session.commit() return True
class TypeCalled(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) type = db.Column(db.String(100), nullable=False, unique=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)
class Clan(db.Model): __tablename__ = 'clan' id = db.Column(db.Integer, primary_key=True) clantag = db.Column(db.String(20), index=True, unique=True) name = db.Column(db.String(64), unique=False)
class Country(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) country = db.Column(db.String(100), nullable=False, unique=True)
class Centro_de_ayuda(db.Model): __tablename__ = 'centro_de_ayuda' id = db.Column(db.Integer, primary_key=True) nombre = db.Column(db.String) telefono = db.Column(db.String) email = db.Column(db.String) sitio_web = db.Column(db.String) hora_de_apertura = db.Column(db.Time) hora_de_cierre = db.Column(db.Time) direccion = db.Column(db.String) protocolo_de_vista = db.Column(db.String) coordenada_x = db.Column(db.Integer) coordenada_y = db.Column(db.Integer) publicado = db.Column(db.Boolean) historico = db.Column(db.Integer) tipos_de_centro = db.relationship('Tipo_de_centro', secondary=tipos_de_centro, backref=db.backref( 'centros_de_ayuda_de_este_tipo', lazy=True), lazy='subquery') municipio_id = db.Column(db.Integer, db.ForeignKey('municipio.id')) municipio = db.relationship('Municipio', back_populates="centros_en_este_municipio") estado_id = db.Column(db.Integer, db.ForeignKey('estado_centro.id')) estado = db.relationship('Estado_centro', back_populates="centros_en_este_estado") def all(): return Centro_de_ayuda.query.filter_by(historico=0).all() def borrar(id): centro = Centro_de_ayuda.query.filter_by(id=id).first() centro.historico = 1 db.session.commit() return True def crear( nombre, direccion,telefono, hapertura, hcierre, email,sitio_web, corx, cory, lista_de_tipos, id_municipio, id_estado,protocolo='PDF', historico=0): tipos = [] for tipo in lista_de_tipos: tipos.append(Tipo_de_centro.query.filter_by(id=tipo).first()) # print("Entre al crear del modelo") nuevo_centro = Centro_de_ayuda(nombre = nombre, direccion = direccion, telefono = telefono, hora_de_apertura = hapertura, hora_de_cierre=hcierre, email=email, sitio_web=sitio_web, tipos_de_centro=tipos, protocolo_de_vista=protocolo, coordenada_y=cory, coordenada_x=corx, historico = historico, municipio_id=id_municipio, estado_id=id_estado, publicado=False) # print("Se creo en memoria el nuevo centro") db.session.add(nuevo_centro) db.session.commit() return nuevo_centro def set_protocolo(id,fn): centro = Centro_de_ayuda.query.get(id) centro.protocolo_de_vista = fn db.session.commit() return True def editar(id, nombre, direccion,telefono, hapertura, hcierre, email,sitio_web, corx, cory, lista_de_tipos, id_municipio, id_estado,protocolo='PDF', historico=0): centro = Centro_de_ayuda.query.get(id) centro.nombre = nombre centro.direccion = direccion centro.telefono = telefono centro.hora_de_apertura = hapertura centro.hora_de_cierre = hcierre centro.sitio_web = sitio_web centro.email = email centro.protocolo_de_vista = protocolo centro.coordenada_x = corx centro.coordenada_y = cory centro.historico = historico tipos = [] for tipo in lista_de_tipos: tipos.append(Tipo_de_centro.query.filter_by(id=tipo).first()) centro.tipos_de_centro=tipos db.session.commit() return True def existe_nombre(municipio_id,nombre): return Centro_de_ayuda.query.filter_by(municipio_id=municipio_id,nombre=nombre).first() def get_by_id(id): return Centro_de_ayuda.query.get(id) def aprobar(id): centro = Centro_de_ayuda.query.get(id) centro.estado = Estado_centro.query.filter_by(nombre='aceptado').first() db.session.commit() return True def rechazar(id): centro = Centro_de_ayuda.query.get(id) centro.estado = Estado_centro.query.filter_by(nombre='rechazado').first() db.session.commit() return True def publicar(id): centro = Centro_de_ayuda.query.get(id) centro.publicado = 1 db.session.commit() return True def despublicar(id): centro = Centro_de_ayuda.query.get(id) centro.publicado = 0 db.session.commit() return True def publicados(): return Centro_de_ayuda.query.filter_by(publicado=True).all() def hola_mundo(): print("Hola mundo") return True
class Course(db.Model, Base): """Model for Udemy course db table.""" __tablename__ = "courses" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) link = db.Column(db.String) # link to include referral code description = db.Column(db.String) imageName = db.Column(db.String) # name of image to display coupons = db.relationship("Coupon") def __init__( self, name: str, link: str, description: str, imageName: str, coupons: List[CouponDict] = [], ): """Create record and add to db.""" self.name = name self.link = link self.description = description self.imageName = imageName if len(coupons) > 0: self.set_coupons(coupons) self.update_db() def set_coupons(self, newCoupons: List[CouponDict]) -> None: """Set coupon property.""" self.coupons = [] for coupon in newCoupons: if "id" in coupon: # this is already in the db, no need to make a new one coupon_obj = Coupon.query.get(coupon["id"]) coupon_obj.update(coupon) self.coupons.append(coupon_obj) else: # not in db, need to make a new one # don't update the database yet, otherwise SQAlchemy gets confused newCoupon = Coupon(**coupon, update_db=False) self.coupons.append(newCoupon) @property def bestCoupon(self) -> CouponDict: """Return dicts for all valid coupon codes for course.""" bestCoupon = None for coupon in self.coupons: if not coupon.is_valid(): continue if bestCoupon is None: bestCoupon = coupon continue # is the price better than the current bestCoupon? if coupon.price < bestCoupon.price: bestCoupon = coupon continue # if price is the same, is expiration better? if coupon.price == bestCoupon.price: if coupon.utcExpirationISO > bestCoupon.utcExpirationISO: bestCoupon = coupon # at the end of it all, who's the winner? if bestCoupon is None: return None return bestCoupon.to_dict() def update_from_patch(self, json_patch: Dict): """Update based on JsonPatch.""" # update to_dict output to have all coupons rather than just the "best" current_data = self.to_dict() if self.coupons is not None: current_data["coupons"] = [c.to_dict() for c in self.coupons] # remove bestCoupon if "bestCoupon" in current_data: del current_data["bestCoupon"] # Apply patch to existing dict updated_data = jsonpatch.apply_patch(current_data, json_patch) # handle coupons separately if "coupons" in updated_data: self.set_coupons(updated_data["coupons"]) del updated_data["coupons"] # Apply the patched dictionary back to the model for key, value in updated_data.items(): setattr(self, key, value) self.update_db() def to_dict(self): """Return the called upon resource to dictionary format.""" return { "id": self.id, "name": self.name, "description": self.description, "link": self.link, "imageName": self.imageName, # defer to JS for camel case "bestCoupon": self.bestCoupon, "coupons": [c.to_dict() for c in self.coupons if c.is_valid()], } def __repr__(self): """Return a pretty print version of the course.""" return f""" < Course(id={self.id},
class ClassifiedTags(db.Model, CRUDMixin): __tablename__ = 'classified_tags' name = db.Column(db.String(255), nullable=False)
from app.db import db from datetime import datetime from flask import session from requests import get tipos_de_centro = db.Table('centro_tiene_tipo', db.Column('centro_id', db.Integer, db.ForeignKey( 'centro_de_ayuda.id'), primary_key=True), db.Column('tipo_de_centro_id', db.Integer, db.ForeignKey( 'tipo_de_centro.id'), primary_key=True) ) class Centro_de_ayuda(db.Model): __tablename__ = 'centro_de_ayuda' id = db.Column(db.Integer, primary_key=True) nombre = db.Column(db.String) telefono = db.Column(db.String) email = db.Column(db.String) sitio_web = db.Column(db.String) hora_de_apertura = db.Column(db.Time) hora_de_cierre = db.Column(db.Time) direccion = db.Column(db.String) protocolo_de_vista = db.Column(db.String) coordenada_x = db.Column(db.Integer) coordenada_y = db.Column(db.Integer) publicado = db.Column(db.Boolean) historico = db.Column(db.Integer) tipos_de_centro = db.relationship('Tipo_de_centro', secondary=tipos_de_centro, backref=db.backref( 'centros_de_ayuda_de_este_tipo', lazy=True), lazy='subquery')
from app.db import db, CRUDMixin, TimestampMixin class ClassifiedAd(db.Model, CRUDMixin, TimestampMixin): __tablename__ = 'classified_ad' name = db.Column(db.String(255), nullable=False) description = db.Column(db.Text) publisher = db.Column(db.String(255), nullable=False) phone = db.Column(db.String(80)) email = db.Column(db.String(255)) user_id = db.Column(db.Integer, db.ForeignKey('users.id')) image = db.Column(db.LargeBinary) categories = db.relationship('ClassifiedTags', secondary='ads_tags_rel', lazy='subquery', backref=db.backref('ads', lazy=True)) class ClassifiedTags(db.Model, CRUDMixin): __tablename__ = 'classified_tags' name = db.Column(db.String(255), nullable=False) adds_tags_rel = db.Table( 'ads_tags_rel', db.Model.metadata, db.Column('ad_id', db.Integer, db.ForeignKey('classified_ad.id')), db.Column('tag_id', db.Integer, db.ForeignKey('classified_tags.id')))
from app.db import db permission_user_table = db.Table('permission_user', db.Model.metadata, db.Column( 'permission_id', db.Integer, db.ForeignKey('permissions.id') ), db.Column( 'user_id', db.Integer, db.ForeignKey('users.id') ) ) permission_role_table = db.Table('permission_role', db.Model.metadata, db.Column( 'permission_id', db.Integer, db.ForeignKey('permissions.id') ), db.Column( 'role_id', db.Integer, db.ForeignKey('roles.id') ) ) category_product_table = db.Table('category_product', db.Model.metadata, db.Column( 'category_id',
) old_price = db.Column( db.Float ) cost_of_purchase = db.Column( db.Float ) discount_id = db.Column( db.Integer ) has_discount_applied = db.Column( db.Boolean server_default="0" ) stock_qty = db.Column( db.Integer ) min_stock_qty = db.Column( db.Integer ) date_created = db.Column( db.DateTime, default=db.func.current_timestamp() ) date_modified = db.Column( db.DateTime, default=db.func.current_timestamp(), onupdate=db.func.current_timestamp() ) attributes = db.relationship( 'Attribute',
class Process(db.Model): __tablename__ = 'processes' uuid = db.Column(db.Text, primary_key=True) pid = db.Column(db.Text, default='') script_path = db.Column(db.Text, default='') arguments = db.Column(db.Text, default='') env_vars = db.Column(db.Text, default='') interpreter_path = db.Column(db.Text, default='') working_dir = db.Column(db.Text, default='') aim_experiment = db.Column(db.Text, default='') executable_id = db.Column(db.Text, default='') created_at = db.Column(db.DateTime, default=default_created_at) is_archived = db.Column(db.Boolean) def __init__(self, executable_id, pid, script_path=None, arguments=None, env_vars=None, interpreter_path=None, working_dir=None, aim_experiment=None): self.uuid = str(uuid.uuid1()) self.executable_id = executable_id self.pid = pid self.script_path = script_path self.arguments = arguments self.env_vars = env_vars self.interpreter_path = interpreter_path self.working_dir = working_dir self.aim_experiment = aim_experiment self.is_archived = False
class CustomerDetails(db.Model): id = db.Column(db.Integer, primary_key=True) age = db.Column(db.Integer, nullable=False) job = db.Column(db.Unicode(100), nullable=False) marital = db.Column(db.Unicode(50), nullable=False) education = db.Column(db.Unicode(50), nullable=False) default = db.Column(db.Unicode(10), nullable=False) balance = db.Column(db.BigInteger, nullable=False) housing = db.Column(db.Unicode(10), nullable=False) loan = db.Column(db.Unicode(10), nullable=False) contact = db.Column(db.Unicode(10), nullable=False) day = db.Column(db.Integer, nullable=False) month = db.Column(db.Unicode(10), nullable=False) duration = db.Column(db.Integer, nullable=False) campaign = db.Column(db.Integer, nullable=False) pdays = db.Column(db.Integer, nullable=False) previous = db.Column(db.Integer, nullable=False) poutcome = db.Column(db.Unicode(10), nullable=False) y = db.Column(db.Unicode(5), nullable=False)
class Executable(db.Model): __tablename__ = 'executables' uuid = db.Column(db.Text, primary_key=True) name = db.Column(db.Text, default='') script_path = db.Column(db.Text) arguments = db.Column(db.Text, default='') env_vars = db.Column(db.Text, default='') interpreter_path = db.Column(db.Text, default='') working_dir = db.Column(db.Text, default='') aim_experiment = db.Column(db.Text, default='') created_at = db.Column(db.DateTime, default=default_created_at) is_archived = db.Column(db.Boolean) is_hidden = db.Column(db.Boolean, default=False) def __init__(self, name, script_path, arguments=None, env_vars=None, interpreter_path=None, working_dir=None, aim_experiment=None): self.name = name self.script_path = script_path self.arguments = arguments self.env_vars = env_vars self.interpreter_path = interpreter_path self.working_dir = working_dir self.aim_experiment = aim_experiment self.uuid = str(uuid.uuid1()) self.is_archived = False self.is_hidden = False
class Usuarios(db.Model, BaseModelMixin): __tablename__ = "USUARIOS" idUsuario = db.Column(db.Integer, primary_key=True) nombreUsuario = 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) direccion = db.Column(db.String) email = db.Column(db.String) password = db.Column(db.String) subastas = db.relationship('Subastas', backref='Usuarios', lazy=True)
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) productos_supermercado = db.relationship('Productos_Supermercados', backref='Productos', lazy=True) def save_to_db(self): db.session.add(self) db.session.commit() def delete_pro(self): db.session.delete(self) db.session.commit() @classmethod def get_query(self, idProducto): filtro = Productos.query.get(idProducto) return filtro @classmethod def get_joins(self): filtro = db.session.query(Categorias, Sub_Categorias, Tipos_Productos, Productos, Productos_Supermercados,Supermercados ). \ outerjoin(Sub_Categorias, Categorias.idCategoria == Sub_Categorias.idCategoria). \ outerjoin(Tipos_Productos, Sub_Categorias.idSubCategorias == Tipos_Productos.idSubCategorias). \ outerjoin(Productos, Tipos_Productos.idTipoProducto == Productos.idTipoProducto). \ outerjoin(Productos_Supermercados, Productos.idProducto == Productos_Supermercados.idProducto). \ outerjoin(Supermercados, Productos_Supermercados.idSupermercado == Supermercados.idSupermercado) # print(filtro) return filtro @classmethod def get(self, idProducto): filtro = db.session.query(Productos).filter( Productos.idProducto == idProducto) return filtro @classmethod def get_Max(self): filtro = Productos.query.filter( Productos.idProducto == db.session.query( func.max(Productos.idProducto))) return filtro @classmethod def get_productos(self, nombreProducto): filtro = Productos.query.filter( or_(Productos.nombreProducto.ilike('%' + nombreProducto + '%'), Productos.contenidoProducto.ilike('%' + nombreProducto + '%'))) return filtro def __init__(self, idTipoProducto, nombreProducto, contenidoProducto, Imagen, codProducto, marca, presentacion, unidadMedida, cantidadPaquete): #self.idProducto = idProducto self.idTipoProducto = idTipoProducto self.nombreProducto = nombreProducto self.contenidoProducto = contenidoProducto self.Imagen = Imagen self.codProducto = codProducto self.marca = marca self.presentacion = presentacion self.unidadMedida = unidadMedida self.cantidadPaquete = cantidadPaquete
class RefPaymentMethod(db.Model): payment_method_code = db.Column(db.String, primary_key=True) payment_method_description = db.Column(db.String)
class Reason(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) reason = db.Column(db.String(100), nullable=False, unique=True)
def update(self): db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def __repr__(self): return f''' <Author id: {self.id}, name: {self.name}, surname: {self.surname}, email: {self.email}, description: {self.description}, technologies: {self.technologies} projects: {self.projects} >''' author_technology = db.Table( 'author_technology', db.Column('author_id', db.Integer, db.ForeignKey('author.id'), primary_key=True), db.Column('technology_id', db.Integer, db.ForeignKey('technology.id'), primary_key=True))
class Estado(db.Model, BaseModelMixin): __tablename__ = "ESTADO" idEstado = db.Column(db.Integer, primary_key=True) nombreEstado = db.Column(db.String) subastas = db.relationship('Subastas', backref='Estado', lazy=True)
class Game(BaseModel): __tablename__ = 'games' id = db.Column( db.Integer, primary_key=True ) season_id = db.Column( db.Integer, index=True, unique=False, nullable=False ) player_count = db.Column( db.Integer, index=True, unique=False, nullable=False ) game_number = db.Column( db.Integer, index=False, unique=False, nullable=False ) start_date = db.Column( db.DateTime, index=False, unique=False, nullable=True ) created_at = db.Column( db.DateTime, index=False, unique=False, nullable=True, default=datetime.datetime.utcnow ) updated_at = db.Column( db.DateTime, index=False, unique=False, nullable=True, default=datetime.datetime.utcnow ) def get_total_player_count(self): sql = f""" SELECT COUNT(*) as total FROM games_placements INNER JOIN games ON games.id = games_placements.game_id WHERE games.id = {self.id} GROUP BY games.id""" game_result = db_fetch(sql) return game_result[0]['total'] def populate_game_results(usernames_and_placements: dict, season_id: int, game_number: int, start_date: str): game = Game.query.filter_by(game_number=game_number, season_id=season_id).first() if game is None: # create game model if not exists game = Game(game_number=game_number, season_id=season_id, start_date=get_datetime_from_string(start_date)) game.save() # delete all existing games placements db.session.query(GamePlacement).filter_by(game_id=game.id).delete() db.session.commit() for username in usernames_and_placements: player = Player.query.filter_by(username=username).first() if player is None: # create player if not exists player = Player(username=username) player.save() placement = usernames_and_placements[username] # create game_placement game_placement = GamePlacement(player_id=player.id, game_id=game.id, placement=placement) game_placement.save() # update player count game.player_count = game.get_total_player_count() game.save()
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) 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) subastas = db.relationship('Subastas', backref='Usuarios', lazy=True) @classmethod def get_joins_filter_obtener_direcciones(self, idUsuarioGet): filtro = Usuarios.query.filter(Usuarios.idUsuario.in_((idUsuarioGet))) return filtro @classmethod def find_by_id(cls, id): print("entro a find_by_id") return cls.query.get(id)
class Season(BaseModel): __tablename__ = 'seasons' id = db.Column( db.Integer, primary_key=True ) name = db.Column( db.String(255), index=False, nullable=False ) champion_id = db.Column( db.Integer, index=True, unique=False, nullable=True ) club_id = db.Column( db.Integer, index=True, unique=False, nullable=True ) season_number = db.Column( db.Integer, index=False, unique=False, nullable=True ) link = db.Column( db.String(255), index=False, unique=False, nullable=True ) created_at = db.Column( db.DateTime, index=False, unique=False, nullable=True, default=datetime.datetime.utcnow ) updated_at = db.Column( db.DateTime, index=False, unique=False, nullable=True, default=datetime.datetime.utcnow ) @classmethod def create_new_season(cls, season_number): # season = Season() # season.name = "NL Hold'Em Season " + str(season_number) # season.club_id = 1 # season.season_number = season_number # season.id = season_number # season.save() sql = f""" INSERT INTO placement_points (placement, points, player_count, season_id) SELECT placement, points, player_count, {season_number} FROM placement_points WHERE season_id = {season_number - 1}; """ print(sql) db_execute(sql) def get_season_results(self): sql = f""" SELECT CASE WHEN players.id = 4 AND seasons.id = 4 THEN SUM(placement_points.points) + 1 ELSE SUM(placement_points.points) END as total_points, players.username, players.id as player_id, seasons.id as season_id, GROUP_CONCAT( CASE WHEN placement_points.placement = 1 THEN '1st' WHEN placement_points.placement = 2 THEN '2nd' WHEN placement_points.placement = 3 THEN '3rd' ELSE CONCAT(placement_points.placement, 'th') END ORDER BY games.start_date ASC SEPARATOR ', ' ) as placements FROM games JOIN seasons on games.season_id = seasons.id JOIN games_placements on games_placements.game_id = games.id JOIN players on players.id = games_placements.player_id JOIN placement_points on placement_points.player_count = games.player_count AND placement_points.season_id = games.season_id AND games_placements.placement = placement_points.placement WHERE seasons.id = {self.id} GROUP BY players.id ORDER BY total_points DESC""" season_leaderboard_results = db_fetch(sql) hash = {} current_placement = 0 for leaderboard_result in season_leaderboard_results: if leaderboard_result['total_points'] not in hash.keys(): current_placement = current_placement + 1 leaderboard_result['placement'] = make_ordinal(current_placement) hash[leaderboard_result['total_points']] = True else: leaderboard_result['placement'] = make_ordinal(current_placement) return season_leaderboard_results def get_game_results_for_season(self): sql = f""" ( SELECT game_number, games.player_count as total_players, games.id as id, games.season_id as season_id, CASE WHEN placement_points.placement = 1 THEN "1st" WHEN placement_points.placement = 2 THEN "2nd" WHEN placement_points.placement = 3 THEN "3rd" ELSE CONCAT(placement_points.placement, "th") END as placement, players.username, placement_points.points as points_earned FROM games JOIN seasons on games.season_id = seasons.id JOIN games_placements on games_placements.game_id = games.id JOIN players on players.id = games_placements.player_id JOIN placement_points on placement_points.player_count = games.player_count AND placement_points.season_id = games.season_id AND games_placements.placement = placement_points.placement WHERE seasons.id = {self.id} ORDER BY game_number DESC, points_earned DESC ) UNION ( SELECT game_number, games.player_count as total_players, games.id as id, games.season_id as season_id, NULL as placement, players.username, 0 as points_earned FROM games JOIN seasons on games.season_id = seasons.id JOIN games_placements on games_placements.game_id = games.id JOIN players on players.id = games_placements.player_id WHERE games_placements.placement IS NULL AND seasons.id = {self.id} ORDER BY game_number DESC, points_earned DESC ) ORDER BY game_number DESC, points_earned DESC""" season_game_results = db_fetch(sql) hash = {} for game_result in season_game_results: if game_result['game_number'] not in hash.keys(): hash[game_result['game_number']] = [] hash[game_result['game_number']].append(game_result) return hash
import uuid import datetime from sqlalchemy.orm import relationship from app.db import db from app.utils import default_created_at CommitTagAssociation = db.Table('commit_tag', db.Column('commit_id', db.Text, db.ForeignKey('commits.uuid')), db.Column('tag_id', db.Text, db.ForeignKey('tags.uuid'))) class Commit(db.Model): __tablename__ = 'commits' uuid = db.Column(db.Text, primary_key=True) hash = db.Column(db.Text) tags = relationship('Tag', secondary=CommitTagAssociation) created_at = db.Column(db.DateTime, default=default_created_at) is_archived = db.Column(db.Boolean) def __init__(self, hash): self.uuid = str(uuid.uuid1()) self.hash = hash self.is_archived = False class Tag(db.Model): __tablename__ = 'tags'
class Property(db.Model, json.Serialisable): __tablename__ = 'property' id = db.Column(db.Integer(), primary_key=True) case_id = db.Column(db.Integer(), db.ForeignKey('case.id', ondelete="CASCADE"), nullable=False, unique=True) title_number = db.Column(db.String(), nullable=False) street = db.Column(db.String(), nullable=False) extended = db.Column(db.String(), nullable=True) locality = db.Column(db.String(), nullable=False) postcode = db.Column(db.String(), nullable=False) tenure = db.Column(db.String(), nullable=False) def __init__(self, case_id, title_number, street, tenure, locality, postcode, extended=None): self.case_id = case_id self.title_number = title_number self.street = street self.extended = extended self.locality = locality self.postcode = postcode self.tenure = tenure def json_format(self): jsondata = {} def append(name, parameter): value = parameter(self) if value is not None: jsondata[name] = value append('id', lambda obj: obj.id) append('case_id', lambda obj: obj.case_id) append('title_number', lambda obj: obj.title_number) append('street', lambda obj: obj.street) append('extended', lambda obj: obj.extended) append('locality', lambda obj: obj.locality) append('postcode', lambda obj: obj.postcode) append('tenure', lambda obj: obj.tenure) return jsondata def object_hook(dct): _id = dct.get('id') _case_id = dct.get('case_id') _title_number = dct.get('title_number') _street = dct.get('street') _extended = dct.get('extended', None) _locality = dct.get('locality') _postcode = dct.get('postcode') _tenure = dct.get('tenure') property_ = Property(_case_id, _title_number, _street, _tenure, _locality, _postcode, _extended) property_.id = _id return property_
class Talk(db.Model, Base): """Model for course talk db table.""" __tablename__ = "talks" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) utcDateStringISO = db.Column(db.Date, nullable=False) description = db.Column(db.String, nullable=False) slidesFilename = db.Column(db.String, nullable=False) conferenceName = db.Column(db.String, nullable=False) conferenceLink = db.Column(db.String, nullable=False) recordingLink = db.Column(db.String, nullable=False) def __init__( self, title: str, localDateStringISO: str, description: str, slidesFilename: str, conferenceName: str, conferenceLink: str, recordingLink: str, ): """Add record to database.""" self.title = title self.utcDateStringISO = dateutil.parser.parse(localDateStringISO) self.description = description self.slidesFilename = slidesFilename self.conferenceName = conferenceName self.conferenceLink = conferenceLink self.recordingLink = recordingLink self.update_db() def update_from_patch(self, json_patch: Dict): """Update based on JsonPatch.""" # get existing data current_data = self.to_dict() # Apply patch to existing dict updated_data = jsonpatch.apply_patch(current_data, json_patch) # Apply the patched dictionary back to the model for key, value in updated_data.items(): setattr(self, key, value) self.update_db() def to_dict(self): """Return the called upon resource to dictionary format.""" return { "id": self.id, "title": self.title, "utcDateStringISO": date.isoformat(self.utcDateStringISO), "description": self.description, "slidesFilename": self.slidesFilename, "conferenceName": self.conferenceName, "conferenceLink": self.conferenceLink, "recordingLink": self.recordingLink, } def __repr__(self): """Return a pretty print version of the retrieved resource.""" return f"""<Talk (id={self.id}, title={self.title}>"""
class Category(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) created_at = db.Column(db.DateTime, default=datetime.now()) updated_at = db.Column(db.DateTime, default=datetime.now())