class Meetup(db.Model): __tablename__ = "meetups" id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) name = db.Column(db.String(50), nullable=False) description = db.Column(db.Text, nullable=False) city = db.Column(db.String(50), nullable=False) state = db.Column(db.String(25), nullable=False) lat = db.Column(db.Numeric(scale=7)) lng = db.Column(db.Numeric(scale=7)) date = db.Column(db.DateTime, nullable=False) created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) updated_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) user = db.relationship("User", back_populates="meetups") def to_dict(self): return { "id": self.id, "user": MinimalUserResponse.from_orm(self.user).dict(), "name": self.name, "description": self.description, "city": self.city, "state": self.state, "lat": float(self.lat or 0), "lng": float(self.lng or 0), "date": self.date, "created_at": self.created_at, "updated_at": self.updated_at, }
class WpAuthKey(db.Model): __tablename__ = "wpti_proxy_tmp_keys" id = db.Column(db.BigInteger(), primary_key=True) creation_time = db.Column(db.DateTime, default=datetime.datetime.utcnow) uuid = db.Column(db.String(60), nullable=False) role = db.Column(db.String(255)) def __str__(self): return "<Uuid: %s>" % self.uuid
class Retailer(db.Model): __tablename__ = "retailers" id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) name = db.Column(db.String(50), nullable=False) description = db.Column(db.Text, nullable=False) city = db.Column(db.String(50), nullable=False) state = db.Column(db.String(25), nullable=False) lat = db.Column(db.Numeric(scale=7)) lng = db.Column(db.Numeric(scale=7)) created_at = db.Column( db.DateTime, nullable=False, default=datetime.datetime.utcnow ) updated_at = db.Column( db.DateTime, nullable=False, default=datetime.datetime.utcnow ) user = db.relationship("User", back_populates="retailers") images = db.relationship("RetailerImage", back_populates="retailer") ratings = db.relationship("RetailerRating", back_populates="retailer") def to_dict(self): return { "id": self.id, "owner": MinimalUserResponse.from_orm(self.user).dict(), "name": self.name, "description": self.description, "city": self.city, "state": self.state, "lat": float(self.lat or 0), "lng": float(self.lng or 0), "created_at": self.created_at, "images": [image.image_url for image in self.images], "ratings": {rating.user_id: rating.to_dict() for rating in self.ratings}, } def to_simple_dict(self): return { "id": self.id, "owner": MinimalUserResponse.from_orm(self.user).dict(), "name": self.name, "description": self.description, "city": self.city, "state": self.state, "created_at": self.created_at, "ratings": [rating.to_dict() for rating in self.ratings], }
class Community(db.Model): __tablename__ = "communities" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False) description = db.Column(db.Text, nullable=False) created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) updated_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) posts = db.relationship("Post", back_populates="community") def to_simple_dict(self): return { "id": self.id, "name": self.name, } def to_dict(self): return { "id": self.id, "name": self.name, "description": self.description, "created_at": self.created_at, }
class Message(db.Model): __tablename__ = "messages" id = db.Column(db.Integer, primary_key=True) sender_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) recipient_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) body = db.Column(db.String(255), nullable=False) created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) updated_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) sender = db.relationship("User", foreign_keys=[sender_id], back_populates="sent_messages") recipient = db.relationship("User", foreign_keys=[recipient_id], back_populates="received_messages") def to_dict(self): return { "id": self.id, "sender": MinimalUserResponse.from_orm(self.sender).dict(), "recipient": MinimalUserResponse.from_orm(self.recipient).dict(), "created_at": self.created_at, }
class User(UserMixin, db.Model, ModelMixin): __tablename__ = "dashboard_users" id = db.Column(db.BigInteger(), primary_key=True) role = db.Column(db.String(255)) def __repr__(self): return f"<id: {self.id}, role: {self.role}>"
class Chat(TimedBaseModel): __tablename__ = "chats" id = db.Column(db.BigInteger, primary_key=True, index=True) type = db.Column(db.String) is_official = db.Column(db.Boolean, server_default=expression.false()) language = db.Column(db.String(12), default="en") join_filter = db.Column(db.Boolean, server_default=expression.false())
class Tag(db.Model): __tablename__ = "tags" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False) description = db.Column(db.String(100), nullable=True) created_at = db.Column( db.DateTime, nullable=False, default=datetime.datetime.utcnow ) updated_at = db.Column( db.DateTime, nullable=False, default=datetime.datetime.utcnow ) def to_dict(self): return { "id": self.id, "name": self.name, "description": self.description, "created_at": self.created_at, }
class Band(db.Model): __tablename__ = 'band' id = db.Column(db.Integer, primary_key=True, index=True) name = db.Column(db.String(30)) #not null state = db.Column(db.Integer, db.ForeignKey('state.id')) #not null pic = db.Column(db.String(200)) review = db.Column(db.String(5000)) def __init__(self, name, state): self.name = name self.state = state def __repr__(self): return \ '<name %r, state %r' % ( self.name, self.state) def createBand(self, name, state): logging.info('Creando Banda: %r' % name) checkBandName = len(name) <= properties.maxBandName if checkBandName: band = Band(name, state) logging.info('Banda creada') return band.save() else: logging.info("Error creando banda") return properties.responsaBandNotCreated def getBands(self): logging.info("Obteniendo bandas") result = self.query.all() return result def getBandsByStateId(self, state): logging.info('Obteniendo bandas por estado: %r' % state) bands = self.query.filter_by(state=state).all() return bands def getBandsByName(self, name): logging.info('Obteniendo bandas por nombre: %r' % name) bands = self.query.filter(Band.name.like("%name%")).all() return bands def getBandById(self, id): logging.info('Obteniendo banda por id: %r' % id) band = self.query.filter_by(id=id).first() return band def setBandPic(self, pic): self.pic = pic def setBandReview(self, review): self.review = review def update(self): try: db.session.commit() return properties.responseBandUpdated except: db.session.rollback() return properties.responseBandNotUpdated def save(self): try: db.session.add(self) db.session.commit() return properties.responseBandCreated except: db.session.rollback() return properties.responseBandNotCreated def delete(self): try: band = self.getBandById(self.id) db.session.delete(band) db.session.commit() return properties.responseBandDeleted except: db.session.rollback() return properties.responseBandNotDeleted
class New(db.Model): __tablename__ = 'new' id = db.Column(db.Integer, primary_key=True, index=True) type = db.Column(db.String(30)) date = db.Column(db.DateTime, default=datetime.datetime.now()) title = db.Column(db.String(100)) pic = db.Column(db.String(200)) content = db.Column(db.String(5000)) def __init__(self, type, date, title, pic, content): self.type = type self.date = date self.title = title self.pic = pic self.content = content def __repr__(self): return \ '<title %r, date %r>' % ( self.title, self.date) def createNew(self, type, date, title, pic, content): logging.info('Creando Noticia: %r' % title) checkNewType = type in properties.newTypes if checkNewType: new = New(type, date, title, pic, content) res = new.save() logging.info('Noticia creada') return res else: logging.info('Error al crear noticia') return properties.responseNewInvalidType def getNews(self, type): logging.info("Obteniendo noticia") result = self.query.filter(New.type.like(type)).all() return result def getNewById(self, id): logging.info('Obteniendo noticia por id: %r' % id) new = self.query.filter_by(id=id).first() return new def getNewsByDate(self, type, startDate, endDate): logging.info('Obteniendo noticia por fecha: %r hasta %r ' % (startDate, endDate)) if startDate is None: news = self.query.filter( and_(New.date <= endDate, New.type == type)).all() else: news = self.query.filter( and_(New.date <= endDate, New.date >= startDate, New.type == type)).all() return news def getNewsByTitle(self, type, title): logging.info('Obteniendo noticia por titulo: %r' % title) news = self.query.filter( and_(New.name.like("%name%"), New.type == type)).all() return news def update(self): try: db.session.commit() return properties.responseNewUpdated except: db.session.rollback() return properties.responseNewNotUpdated def save(self): db.session.add(self) try: db.session.commit() return properties.responseNewCreated except: db.session.rollback() return properties.responseNewNotCreated def delete(self): try: new = self.getBandById(self.id) db.session.delete(new) db.session.commit() return properties.responseNewDeleted except: db.session.rollback() return properties.responseNewNotDeleted
class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True, index=True) email = db.Column(db.String(30), unique=True) fullname = db.Column(db.String(50)) password = db.Column(db.String(200)) rol = db.Column(db.Integer) def __init__(self, email, fullname, password, rol): self.email = email self.fullname = fullname self.password = password self.rol = rol def __repr__(self): return \ '<fullname %r, email %r, password %r, rol %r >' % ( self.fullname, self.email, self.password, self.rol) def getUsers(self): logging.info("Obteniendo usuarios") result = self.query.all() return result def getUserByEmail(self, email): logging.info('Obteniendo usuario por email: %r' % email) user = self.query.filter_by(email=email).first() return user def getUserById(self, id): logging.info('Obteniendo usuario por id: %r' % id) user = self.query.filter_by(id=id).first() return user def createUser(self, email, fullname, password, rol): logging.info('Creando Usuario: %r' % email) rol = rol or 1 checkLongEmail = len(email) <= properties.maxEmail checkLongFullname = len(fullname) <= properties.maxFullName checkLongPassword = len(password) <= properties.maxPassword if checkLongEmail and checkLongFullname and checkLongPassword: foundUser = self.getUserByEmail(email) if foundUser == None: user = User(email, fullname, password, rol) res = user.save() logging.info('Usuario creado') return res else: return properties.responseUserAlreadyExist else: return properties.responseUserInvalidAttributes def update(self): try: db.session.commit() return properties.responseUserUpdated except: db.session.rollback() return properties.responseUserNotUpdated def save(self): try: db.session.add(self) db.session.commit() return properties.responseUserCreated except: db.session.rollback() return properties.responseUserNotCreated def delete(self): try: user = self.getUserById(self.id) db.session.delete(user) db.session.commit() return properties.responseUserDeleted except: db.session.rollback() return properties.responseUserNotDeleted
class Disc(db.Model): __tablename__ = 'disc' id = db.Column(db.Integer, primary_key=True, index=True) name = db.Column(db.String(60)) #not null date = db.Column(db.DateTime, default=datetime.datetime.now()) #not null genre = db.Column(db.String(60)) #not null score = db.Column(db.Integer) band = db.Column(db.Integer, db.ForeignKey('band.id')) #not null cover = db.Column(db.String(200)) review = db.Column(db.String(5000)) def __init__(self, name, date, genre, band): self.name = name self.date = date self.genre = genre self.band = band self.score = 0 def __repr__(self): return \ '<date %r, name %r, band %r >' % ( self.date, self.name, self.band) def createDisc(self, name, date, genre, band): logging.info("Creando disco") checkLongName = len(name) <= properties.maxDiscName checkGenre = len(genre) <= properties.maxGenreName if checkLongName and checkGenre: disc = Disc(name, date, genre, band) logging.info("Disco creado") return disc.save() else: logging.info("Error creando disco") return properties.responseDiscNotCreated def getDiscs(self): logging.info("Obteniendo discos") result = self.query.all() return result def getDiscsByDate(self, startDate, endDate): logging.info('Obteniendo discos por fecha: %r hasta %r ' % (startDate, endDate)) if startDate is None: discs = self.query.filter(Disc.date <= endDate).all() else: discs = self.query.filter( and_(Disc.date <= endDate, Disc.date >= startDate)).all() return discs def getDiscsByGenre(self, genre): logging.info('Obteniendo discos por genero: %r' % genre) discs = self.query.filter_by(genre=genre).all() return discs def getDiscsByScore(self, startScore, endScore): logging.info('Obteniendo discos por puntuacion: %r hasta %r ' % (startScore, endScore)) if startScore is None: discs = self.query.filter(Disc.score <= endScore).all() else: discs = self.query.filter( and_(Disc.score <= endScore, Disc.score >= startScore)).all() return discs def getDiscsByBand(self, band): logging.info('Obteniendo discos por banda: %r' % band) discs = self.query.filter_by(band=band).all() return discs def getDiscsByName(self, name): logging.info('Obteniendo discos por nombre: %r' % name) bands = self.query.filter(Disc.name.like("%" + name + "%")).all() return bands def getDiscById(self, id): logging.info('Obteniendo disco por id: %r' % id) disc = self.query.filter_by(id=id).first() return disc def setDiscScore(self, score): self.score = score def setDiscCover(self, cover): self.cover = cover def setDiscGenre(self, genre): self.genre = genre def setDiscReview(self, review): self.review = review def update(self): try: db.session.commit() return properties.responseDiscUpdated except: db.session.rollback() return properties.responseDiscNotUpdated def save(self): db.session.add(self) try: db.session.commit() return properties.responseDiscCreated except: db.session.rollback() return properties.responseDiscNotCreated def delete(self): try: disc = self.getDiscById(self.id) db.session.delete(disc) db.session.commit() return properties.responseDiscDeleted except: db.session.rollback() return properties.responseDiscNotDeleted
class State(db.Model): __tablename__ = 'state' id = db.Column(db.Integer, primary_key=True, index=True) name = db.Column(db.String(30)) def __init__(self, name): self.name = name def __repr__(self): return \ '<name %r >' % (self.name) def getStates(self): logging.info("Obteniendo estados") result = self.query.all() return result def createState(self, name): logging.info('Creando Estado: %r' % name) checkLongName = len(name) <= properties.maxStateName if checkLongName: foundState = self.getStatesByName(name) if foundState == None: state = State(name) state.save() logging.info('Estado creado') def getStateById(self, id): logging.info('Obteniendo estado por id: %r' % id) try: state = self.query.filter_by(id=id).first() return state except: return None def getStatesByName(self, name): try: logging.info('Obteniendo estado por nombre: %r' % name) state = self.query.filter(State.name.like("%" + name + "%")).all() return state except: return [] def update(self): try: db.session.commit() except: db.session.rollback() def save(self): try: db.session.add(self) db.session.commit() except: db.session.rollback() def delete(self): try: state = self.getStateById(self.id) db.session.delete(state) db.session.commit() except: db.session.rollback()
class Comment(db.Model): __tablename__ = "comments" id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) thread_id = db.Column(db.Integer, db.ForeignKey("threads.id"), nullable=False) comment_id = db.Column(db.Integer, db.ForeignKey("comments.id"), nullable=True) path = db.Column(db.String(255), nullable=False) level = db.Column(db.Integer, nullable=False) body = db.Column(db.Text, nullable=False) created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) updated_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.utcnow) thread = db.relationship("Thread", back_populates="comments") user = db.relationship("User", back_populates="comments") children = db.relationship("Comment", backref=db.backref("parent", remote_side=[id])) ratings = db.relationship("CommentRating", back_populates="comment") def to_simple_dict(self): return { "id": self.id, "body": self.body, "user": MinimalUserResponse.from_orm(self.user).dict(), "comment_id": self.comment_id, } def to_search_dict(self): return { "id": self.id, "body": self.body, "user": MinimalUserResponse.from_orm(self.user).dict(), "post": self.thread.post.to_search_dict(), "ratings": {rating.user_id: rating.to_dict() for rating in self.ratings}, "created_at": self.created_at, } def to_dict(self): return { "id": self.id, "user": MinimalUserResponse.from_orm(self.user).dict(), "body": self.body, "thread_id": self.thread_id, "path": self.path, "level": self.level, "created_at": self.created_at, "updated_at": self.updated_at, "children": [child.to_simple_dict() for child in self.children], "ratings": {rating.user_id: rating.to_dict() for rating in self.ratings}, "post": self.thread.post.to_search_dict(), }
class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True, index=True) type = db.Column(db.String(30)) date = db.Column(db.DateTime, default=datetime.datetime.now()) title = db.Column(db.String(100)) pic = db.Column(db.String(200)) content = db.Column(db.String(5000)) def __init__(self, type, date, title, pic, content): self.type = type self.date = date self.title = title self.pic = pic self.content = content def __repr__(self): return \ '<title %r, date %r>' % ( self.title, self.date) def createArticle(self, type, date, title, pic, content): logging.info('Creando Articulo: %r' % title) checkArticleType = type in properties.articleTypes if checkArticleType: article = Article(type, date, title, pic, content) logging.info('Articulo creado') return article.save() else: logging.info('Error al crear el articulo') return properties.responseArticleInvalidType def getArticles(self, type): logging.info("Obteniendo articulos") result = self.query.filter(Article.type.like(type)).all() return result def getArticleById(self, id): logging.info('Obteniendo articulo por id: %r' % id) article = self.query.filter_by(id=id).first() return article def getArticlesByDate(self, type, startDate, endDate): logging.info('Obteniendo articulos por fecha: %r hasta %r ' % (startDate, endDate)) if startDate is None: articles = self.query.filter( and_(Article.date <= endDate, Article.type == type)).all() else: articles = self.query.filter( and_(Article.date <= endDate, Article.date >= startDate, Article.type == type)).all() return articles def getArticlesByTitle(self, type, title): logging.info('Obteniendo articulos por titulo: %r' % title) articles = self.query.filter( and_(Article.name.like("%name%"), Article.type == type)).all() return articles def update(self): try: db.session.commit() return properties.responseArticleUpdated except: db.session.rollback() return properties.responseArticleNotUpdated def save(self): db.session.add(self) try: db.session.commit() return properties.responseArticleCreated except: db.session.rollback() return properties.responseArticleNotCreated def delete(self): try: article = self.getBandById(self.id) db.session.delete(article) db.session.commit() return properties.responseArticleDeleted except: db.session.rollback() return properties.responseArticleNotDeleted
class Cereal(db.Model): name = db.Column(db.String(80), primary_key=True) mfr = db.Column(db.String(10), nullable=True) type = db.Column(db.String(10), nullable=True) calories = db.Column(db.Float, nullable=True) protein = db.Column(db.Float, nullable=True) fat = db.Column(db.Float, nullable=True) sodium = db.Column(db.Float, nullable=True) fiber = db.Column(db.Float, nullable=True) carbo = db.Column(db.Float, nullable=True) sugars = db.Column(db.Float, nullable=True) potass = db.Column(db.Float, nullable=True) vitamins = db.Column(db.Float, nullable=True) shelf = db.Column(db.Float, nullable=True) weight = db.Column(db.Float, nullable=True) cups = db.Column(db.Float, nullable=True) rating = db.Column(db.Float, nullable=True) active = db.Column(db.Boolean, server_default=expression.true()) @staticmethod def get_cereals() -> List[Cereal]: cereals = Cereal.query.filter_by(active=True).all() return CerealSchema(many=True).dump(cereals) @staticmethod def get_cereal(name: str) -> Cereal: cereal = Cereal.query.filter_by(name=name, active=True).first() return CerealSchema().dump(cereal) @staticmethod def post_cereal(cereal: Cereal) -> Cereal: cereal = Cereal(name=cereal.get('name'), calories=cereal.get('calories'), protein=cereal.get('protein'), fat=cereal.get('fat'), sodium=cereal.get('sodium'), fiber=cereal.get('fiber'), carbo=cereal.get('carbo'), sugars=cereal.get('sugars'), potass=cereal.get('potass'), vitamins=cereal.get('vitamins')) db.session.add(cereal) db.session.commit() return CerealSchema().dump(cereal) @staticmethod def put_cereal(name: str, cereal: Cereal): Cereal.query.filter_by(name=name).update( dict(calories=cereal.get('calories'), protein=cereal.get('protein'), fat=cereal.get('fat'), sodium=cereal.get('sodium'), fiber=cereal.get('fiber'), carbo=cereal.get('carbo'), sugars=cereal.get('sugars'), potass=cereal.get('potass'), vitamins=cereal.get('vitamins'))) db.session.commit() @staticmethod def delete_cereal(name: str): Cereal.query.filter_by(name=name).update(dict(active=False)) db.session.commit()