class UserTable(db.Model): __tablename__ = "usertable" userid = db.Column(UUID(as_uuid=True), primary_key=True) username = db.Column(db.String(50), nullable=False) password = db.Column(db.String(64), nullable=False) email = db.Column(db.String(355), unique=True, nullable=False) admin = db.Column(db.Boolean(), unique=False, nullable=False, default=False) lastlogin = db.Column(db.DateTime) def __init__(self, data): self.userid = str(uuid.uuid1()) self.username = data["username"] self.password = data["password"] self.email = data["email"] self.lastlogin = data["lastlogin"] self.admin = False def serialise(self): return { "userid": str(self.userid), "username": self.username, "email": self.email, "lastlogin": str(self.lastlogin), "admin": False }
class UserModel(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(25), unique=True, nullable=False) password = db.Column(db.String(25), nullable=False) def __init__(self, username=None, password=None): self.username = username self.password = password @classmethod def find_by_username(cls, username: str) -> object: """ Find an user by the given username. :param username: Username to search for the user. :return: Object of the User class. """ return cls.query.filter_by(username=username).first() @classmethod def find_by_id(cls, id_: str) -> object: """ Find a user by the given id. :param id_: ID to search for the user. :return: Object of the User class. """ return cls.query.get(id_) def save_to_db(self) -> None: """ Save to data base. """ db.session.add(self) db.session.commit()
class WeatherData(db.Model): __tablename__ = 'weather_data' id = db.Column(db.Integer, primary_key=True) created = db.Column( db.DateTime, default=datetime.datetime.now( pytz.timezone("Europe/Bratislava")).replace(microsecond=0)) temperature = db.Column(db.String()) humidity = db.Column(db.String()) def __init__(self, humidity, temperature, created): self.humidity = humidity self.temperature = temperature self.created = created def json(self): return { "created": self.created, "temperature": self.temperature, "humidity": self.humidity, } def delete_from_db(self): db.session.delete(self) db.session.commit() def save_to_db(self): db.session.add(self) db.session.commit() @staticmethod def get_data_between_specific_dates(start=None, end=None): try: if start and end: data = WeatherData.query.filter( WeatherData.created <= end).filter( WeatherData.created >= start) return data return {"msg": "Please define START and END dates properly"}, 404 except Exception as e: return { "msg": "Could not get required dates. {error}".format(error=e) }, 500 @classmethod def find_latest(cls): return cls.query.order_by(cls.created.desc()).first() @classmethod def get_all_available_data(cls): """ :return: """ try: weather_data = cls.query.all() return weather_data except Exception as e: print("Could not return weather data: {error}".format(error=e)) return None
class UserModel(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80)) password = db.Column(db.String(80)) def __init__(self, username, password): self.username = username self.password = password def json(self): return { 'id':self.id, 'username':self.username } @classmethod def find_by_username(cls, username): return cls.query.filter_by(username=username).first() @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).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()
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(18), nullable=False, unique=True) password_hash = db.Column(db.String(94)) # Required for administrative interface def __unicode__(self): return self.username
class Game(db.Model, Serializer): id = db.Column(db.String(36), primary_key=True, default=generate_uuid, unique=True) key = db.Column(db.String(KEY_LENGTH), unique=True, default=generate_key) created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) state = db.Column(db.Enum(GameState), default=GameState.WAITING) players = db.relationship('Player', backref='game', lazy=True, cascade="all, delete", foreign_keys=[Player.game_id]) max_players = db.Column(db.Integer) current_player_id = db.Column( db.String(36), db.ForeignKey('player._id', name='current_player_id')) current_player = db.relationship('Player', uselist=False, foreign_keys=[current_player_id], post_update=True) nextVotes = db.relationship('Vote', cascade="all, delete", foreign_keys=[Vote.game_id]) guessVotes = db.relationship('Vote', cascade="all, delete", foreign_keys=[Vote.game_id]) awaitingGuessVote = db.Column(db.Boolean, default=False) used_collections = db.relationship('Collection', secondary=used_collections) def get_connected_players(self): return [player for player in self.players if player.connected] def get_guessing_players(self): return [player for player in self.players if not player.guessed] def get_next_votes(self): return [vote for vote in self.nextVotes if vote.result] def get_correct_guess_votes(self): return [vote for vote in self.guessVotes if vote.result] def get_wrong_guess_votes(self): return [vote for vote in self.guessVotes if not vote.result] def serialize(self): d = Serializer.serialize(self) d['players'] = [{ 'player': player.serialize(), '_id': player._id } for player in self.players] d['correctGuessVotes'] = len(self.get_correct_guess_votes()) d['wrongGuessVotes'] = len(self.get_wrong_guess_votes()) return d def __repr__(self): return '<Game {}>'.format(self.id)
class FileTable(db.Model): __tablename__ = "filetable" fileid = db.Column(UUID(as_uuid=True), primary_key=True) filename = db.Column(db.String(64), nullable=False) extension = db.Column(db.String(16), nullable=False) def __init__(self, data): self.fileid = str(uuid.uuid1()) self.filename = data["filename"] self.extension = data["extension"]
class Image(db.Model, Serializer): id = db.Column(db.String(36), primary_key=True, default=generate_uuid, unique=True) image_url = db.Column(db.String()) license = db.Column(db.String()) creator = db.Column(db.String()) def __repr__(self): return self.image_url.split("/")[-1]
class Character(db.Model, Serializer): id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(80), unique=True, nullable=False) collection_id = db.Column( db.Integer, db.ForeignKey('collection.id', name='collection_id_character')) image_id = db.Column(db.String(36), db.ForeignKey('image.id', name='image_id_character')) image = db.relationship('Image', uselist=False, foreign_keys=[image_id]) def __repr__(self): return '{}'.format(self.name)
class UserModel(Model, db.Model): '''UserModel class Inherits Model base class and db.Model. ''' __tablename__ = 'users' username = db.Column(db.String(32), index=True) password = db.Column(db.String(128)) site_location = db.Column(db.String(80)) admin = db.Column(db.Boolean) super_user = db.Column(db.Boolean) def __init__(self, username, password, site_location, admin, super_user, created_by): '''Mapping from DB to UserModel object occurs in init.''' Model.__init__(self, created_by) self.username = username self.password = password self.site_location = site_location self.admin = admin self.super_user = super_user def save_to_db(self): '''Save user record to DB.''' db.session.add(self) db.session.commit() def delete_from_db(self): '''Delete user record from DB.''' db.session.delete(self) db.session.commit() @classmethod def find_by_username(cls, username): '''Returns user if found by name''' return cls.query.filter_by(username=username).first() @classmethod def find_by_id(cls, _id): '''Returns user if found by ID.''' return cls.query.filter_by(id=_id).first() def json(self): '''Returns JSON object of user.''' return { 'username': self.username, 'password': self.password, 'site_location': self.site_location, 'admin': self.admin, 'super_user': self.super_user }
class UserModel(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80)) # 80 characters limit password = db.Column(db.String(80)) def __init__(self, username, password): self.username = username self.password = password def json(self) -> dict: """ Returns the id & name as .json string. :return: {'id': Int, 'username': String} """ return {'id': self.id, 'username': self.username} @classmethod def find_by_username(cls, username: str) -> object: """ Find an (already registered) user by the given username. :param username: Username to search for the user. :return: Object of the User class. """ return cls.query.filter_by(username=username).first() @classmethod def find_by_id(cls, id_: str) -> object: """ Find a (already registered) use by the given id. :param id_: ID to search for the user. :return: Object of the User class. """ return cls.query.get(id_) def save_to_db(self) -> None: """ Save user to data base. """ db.session.add(self) db.session.commit() def delete_from_db(self) -> None: """ Delete user from database. """ db.session.delete(self) db.session.commit()
class Vote(db.Model, Serializer): id = db.Column(db.Integer, autoincrement=True, primary_key=True) result = db.Column(db.Boolean, default=False) game_id = db.Column(db.String(36), db.ForeignKey('game.id', name='game_id_vote')) player_id = db.Column(db.String(36), db.ForeignKey('player._id', name='player_id_vote')) player = db.relationship('Player', uselist=False, foreign_keys=[player_id], post_update=True) def __repr__(self): return "<Vote {}: {}; game {}>".format(self.id, self.result, self.game_id)
class StoreModel(db.Model): __tablename__ = "tblStores" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) # knows it is a many to one relationship , so this is a list items = db.relationship('ItemModel', lazy='dynamic') def __init__(self, name): self.name = name def json(self): return { "name": self.name, "items": [item.json() for item in self.items.all()] } def check_empty(self): return next((item.json() for item in self.items.all()), None) @classmethod def find_by_name(cls, name): return StoreModel.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()
class ItemModel(db.Model): __tablename__ = 'items' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) price = db.Column(db.Float(precision=2)) store_id = db.Column(db.Integer, db.ForeignKey('stores.id')) store = db.relationship('StoreModel') def __init__(self, name, price, store_id): self.name = name self.price = price self.store_id = store_id def json(self): return {'id': self.id, 'name': self.name, 'price': self.price, 'store_id': self.store_id} @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()
class CommentTable(db.Model): __tablename__ = "commenttable" commentid = db.Column(UUID(as_uuid=True), primary_key=True) fileid = db.Column(UUID(as_uuid=True), db.ForeignKey('filetable.fileid', ondelete='CASCADE'), nullable=False) userid = db.Column(UUID(as_uuid=True), db.ForeignKey('usertable.userid', ondelete='CASCADE'), nullable=False) comment = db.Column(db.String(256), nullable=False) date = db.Column(db.DateTime()) user = db.relationship(UserTable, foreign_keys=userid, backref=db.backref('user', lazy='joined', cascade="all, delete-orphan")) commentFile = db.relationship(FileTable, foreign_keys=fileid, backref=db.backref( 'commentFile', lazy='joined', cascade="all, delete-orphan")) def __init__(self, data): self.commentid = str(uuid.uuid1()) self.fileid = data['fileid'] self.userid = data['userid'] self.comment = data['comment'] self.date = data['date']
class Todo(db.Model): __tablename__ = 'todo' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String()) def __init__(self, name): self.name = name def __repr__(self): return '<id {0}>'.format(self.id) def save(self): db.session.add(self) db.session.commit() return self # FIXME: Validar si se obtiene un objeto def delete(self): db.session.delete(self) db.session.commit() return self def to_dict(self): return { c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs }
class StoreModel(db.Model): __tablename__ = 'stores' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) # 80 characters limit # List of ItemModels; many-to-1 rel. (Back reference) # lazy: to not create an StoreModel for each item yet items = db.relationship( 'ItemModel', lazy='dynamic' ) # self.items is no list anymore but a query builder -> .all() def __init__(self, name): self.name = name def json(self) -> dict: """ Returns the name & items as .json string. :return: {'id': Int, 'name': String, 'items': String} """ return { 'id': self.id, 'name': self.name, 'items': [item.json() for item in self.items.all()] } # List comprehension @classmethod def find_by_name(cls, name: str) -> object: """ Find an object by its name. :param name: Item name to find. :return: object """ return cls.query.filter_by( name=name).first() # SELECT * FROM items WHERE name=name LIMIT 1 @classmethod def find_all(cls) -> tuple: """ Returns all stores in .db :return: All stores found in .db """ return cls.query.all() def save_to_db(self) -> None: """ Insert new or update existing object in data base. """ db.session.add(self) db.session.commit() def delete_from_db(self) -> None: """ Delete object from the data base. """ db.session.delete(self) db.session.commit()
class StoreModel(db.Model): __tablename__ = 'stores' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) items = db.relationship('ItemModel', lazy='dynamic') def __init__(self, name): self.name = name def json(self): return { 'name': self.name, 'items': [item.json() for item in self.items.all()] } @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).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()
class LibraryModel(db.Model): __tablename__ = "libraries" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) books = db.relationship('BookModel', lazy='dynamic') def __init__(self, name): self.name = name def json(self): return { 'id': self.id, 'name': self.name, 'items': [item.json() for item in self.books.all()] } @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()
class Category(Base): __tablename__ = "categories" name = db.Column(db.String(100), nullable=False) products = db.relationship("Product", secondary="categories_products", back_populates="categories", lazy="joined")
class GroupTable(db.Model): __tablename__ = "grouptable" groupid = db.Column(UUID(as_uuid=True), primary_key=True) groupname = db.Column(db.String(64), nullable=False) groupleaderid = db.Column('groupleader', UUID(as_uuid=True), db.ForeignKey('usertable.userid'), nullable=False) groupleader = db.relationship(UserTable, foreign_keys=groupleaderid, backref=db.backref('leader', lazy='joined')) def __init__(self, data): self.groupid = str(uuid.uuid1()) self.groupname = data["groupname"] self.groupleaderid = data["groupleaderid"] def serialise(self): return { "groupid": str(self.groupid), "groupname": str(self.groupname), "groupleaderid": str(self.groupleaderid) }
class Tag(db.Model, Serializer): name = db.Column(db.String(20), unique=True, primary_key=True, nullable=False) def __repr__(self): return '{}'.format(self.name)
class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(100)) password = db.Column(db.String(100)) email = db.Column(db.String(100)) alerts = db.relationship('AlertModel') registerdate = db.Column(db.DateTime, default=datetime.datetime.utcnow()) def __init__(self, username, password, email): self.username = username self.password = password self.email = email self.registerdate = datetime.datetime.utcnow() @classmethod def get_by_username(cls, username): user = cls.query.filter_by(username=username).first() if user: return user return None @classmethod def get_by_email(cls, email): user = cls.query.filter_by(email=email).first() if user: return user return None @classmethod def get_by_id(cls, _id): user = cls.query.filter_by(id=_id).first() if user: return user return None def add_user(self): db.session.add(self) db.session.commit() def delete_user(self): for alert in self.alerts: alert.delete_alert() db.session.delete(self) db.session.commit()
class ItemModel(db.Model): __tabelname__ = 'items' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) price = db.Column(db.Float(precision=2)) # store_id = db.Column(db.Integer, db.ForeignKey('stores.id')) # store = db.relationship('StoreModel') def __init__(self, name, price): self.name = name self.price = price # self.store_id = store_id def json(self): return {'name':self.name,'price':self.price} @classmethod def find_by_name(cls,name): # connection = sqlite3.connect('mydata.db') # cursor = connection.cursor() # # query = "select * from items where name=?" # result = cursor.execute(query, (name,)) # row = result.fetchone() # connection.close() # # if row: # return cls(*row) # cls(row[0],row[1]) return ItemModel.query.filter_by(name=name).first() def save_to_db(self): # def insert(self): # connection = sqlite3.connect('mydata.db') # cursor = connection.cursor() # query = "insert into items values(?,?)" # cursor.execute(query, (self.name, self.price,)) # connection.commit() # connection.close() db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit() # def update(self): # connection = sqlite3.connect('mydata.db') # cursor = connection.cursor() # query = "update items set price=? where name=?" # cursor.execute(query, (self.price, self.name,)) # connection.commit() # connection.close()
class UserModel(db.Model, DBActionMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(USERNAME_LEN), unique=True) hashed_password = db.Column(db.String(HASH_LEN)) salt = db.Column(db.String(SALT_LEN)) def __init__(self, **kwargs): for key, val in kwargs.items(): setattr(self, key, val) @classmethod def find_by_username(cls, username): return cls.query.filter_by(username=username).first() @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first()
class DosarModel(db.Model): __tablename__ = 'dosare' dosarType = { 'fond': 'Fond', 'apel': 'Apel', 'recurs': 'Recurs', 'contestatie': 'Contestatie In Anulare', 'revizuire': 'Revizuire', 'executare': 'Executare Silita', 'faliment': 'Cerere Inscriere la Masa Credala (faliment)' } id = db.Column(db.String(120), primary_key=True) name = db.Column(db.String(60)) type = db.Column(db.String(50)) __table_args__ = (db.UniqueConstraint('name', 'type', name='name_type_uq'), ) def __init__(self, name, _type, _id=None): self.id = _id if _id else str(uuid.uuid4().hex) self.name = name self.type = _type if DosarModel.validate_type(_type) else None @staticmethod def validate_type(type): return DosarModel.dosarType.get(type) def json(self): return {'name': self.name, 'type': DosarModel.dosarType.get(self.type)} @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()
class StoreModel(db.Model): __tabelname__ = 'stores' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) items = db.relationship("ItemModel", back_populates="items") items = db.relationship('ItemModel', lazy='dynamic') def __init__(self, name): self.name = name def json(self): return {'name':self.name,'items':[item.json() for item in self.items.all()]} @classmethod def find_by_name(cls,name): # connection = sqlite3.connect('mydata.db') # cursor = connection.cursor() # # query = "select * from items where name=?" # result = cursor.execute(query, (name,)) # row = result.fetchone() # connection.close() # # if row: # return cls(*row) # cls(row[0],row[1]) #return ItemModel.query.filter_by(name=name).first() return cls.query.filter_by(name=name).first() def save_to_db(self): # def insert(self): # connection = sqlite3.connect('mydata.db') # cursor = connection.cursor() # query = "insert into items values(?,?)" # cursor.execute(query, (self.name, self.price,)) # connection.commit() # connection.close() db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit() # def update(self): # connection = sqlite3.connect('mydata.db') # cursor = connection.cursor() # query = "update items set price=? where name=?" # cursor.execute(query, (self.price, self.name,)) # connection.commit() # connection.close()
class UserModel(db.Model): __tablename__ = 'users' TYPES = [('regular', 'Avocat'), ('admin', 'Administrator')] id = db.Column(db.String(120), primary_key=True) username = db.Column(db.String(80)) password = db.Column(db.String(80)) name = db.Column(db.String(160)) user_type = db.Column(ChoiceType(TYPES)) def __init__(self, username, password, _id=None, name=None, user_type="regular"): self.id = _id if _id else str(uuid.uuid4().hex) self.username = username self.password = password self.name = name if name else username self.user_type = user_type def save_to_db(self): db.session.add(self) db.session.commit() def json(self): return { 'id:' 'username': self.username, 'name': self.name, 'user_type': self.user_type.value } @classmethod def find_by_username(cls, username): return cls.query.filter_by(username=username).first() @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first()
class Cardiaque(OutputMixin, db.Model): __tablename__ = 'cardiaque' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(), nullable=False) rythme = db.Column(db.Integer, primary_key=False) date = db.Column(db.Text, nullable=True) #rythme cardiaque enregistré def __repr__(self): return "{{'id' : '{}', 'email' : '{}', 'rythme' : '{}', 'date' : '{}'}}" \ .format(self.id, self.email, self.rythme, self.date)
class MetadataTable(db.Model): __tablename__ = "metadatatable" metadataid = db.Column(UUID(as_uuid=True), primary_key=True) versionid = db.Column(UUID(as_uuid=True), db.ForeignKey('fileversiontable.versionid', ondelete='CASCADE'), nullable=False) title = db.Column(db.String(64), nullable=False) value = db.Column(db.String(128), nullable=False) version = db.relationship(FileVersionTable, foreign_keys=versionid, backref=db.backref('version', lazy='joined', cascade="all, delete-orphan")) def __init__(self, data): self.metadataid = str(uuid.uuid1()) self.versionid = data["versionid"] self.title = data["title"] self.value = data["value"]