class Subscription(db.Model): """Subscription model. Parameters ---------- db : Model """ __tablename__ = 'subscription' id = db.Column(db.Integer, primary_key=True) started = db.Column(db.DateTime) ended = db.Column(db.DateTime) company_id = db.Column( db.Integer, db.ForeignKey('organization.id') ) company = db.relationship( 'Company', backref='subscriptions')
class RouteRequestModel(db.Model): __tablename__ = "requests" def __init__(self, start_point_lat, start_point_long, end_point_lat, end_point_long): self.start_point_lat = start_point_lat self.start_point_long = start_point_long self.end_point_lat = end_point_lat self.end_point_long = end_point_long id = db.Column(db.Integer, primary_key=True) start_point_lat = db.Column(db.Float, nullable=False) end_point_lat = db.Column(db.Float, nullable=False) start_point_long = db.Column(db.Float, nullable=False) end_point_long = db.Column(db.Float, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) def save_to_db(self): db.session.add(self) db.session.commit()
class SiteMotif(BioModel): name = db.Column(db.String(32)) pattern = db.Column(db.String(32)) site_type_id = db.Column(db.Integer, db.ForeignKey('sitetype.id')) site_type = db.relationship(SiteType, backref='motifs') def generate_pseudo_logo(self, sequences): path = self.pseudo_logo_path sequence_logo(sequences, path=path, title=self.name) @property def pseudo_logo_path(self) -> Path: path = Path('static/logos/') path.mkdir(parents=True, exist_ok=True) safe_name = ''.join(c for c in self.name if c.isalnum()) path /= f'{safe_name}_{self.id}.svg' return path
class Vid(db.Model): __tablename__ = "vids" id = db.Column(db.Integer, primary_key=True) vname = db.Column(db.String(300)) enable = db.Column(db.Integer) ar = db.Column(db.Integer) controls = db.Column(db.Integer) mute = db.Column(db.Integer) vkey = db.Column(db.Integer, db.ForeignKey("media.id", ondelete='cascade'), nullable=True) def __init__(self, vname="Tokyo.mp4", enable=1, ar=1, controls=1, mute=2, vkey=6): self.vname = vname self.enable = enable self.ar = ar self.controls = controls self.mute = mute self.vkey = vkey
class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) login = db.Column(db.String, unique=True, nullable=False) token = db.Column(db.String, nullable=False) role_id = db.Column(db.Integer, db.ForeignKey('roles.id'), nullable=False) role = db.relationship('Role', backref=db.backref('users', lazy=True)) def insert(self): if self.role is None: self.role = get_role("user") self.token = randomword(25) db.session.add(self) db.session.commit() def remove(self): db.session.delete(self) db.session.commit()
class ClassNameModel(db.Model): __tablename__ = 'classes' id = db.Column(db.Integer, primary_key=True) teacher_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) name = db.Column(db.String(100), nullable=False) teacher = db.relationship('UserModel') student_class = db.relationship('StudentClassModel', lazy='dynamic') def __init__(self, teacher_id, name): self.teacher_id = teacher_id self.name = name def save_to_db(self): db.session.add(self) db.session.commit() def json(self): return { 'class_id': self.id, 'teacher_id': self.teacher_id, 'class_name': self.name } def json_name(self): return {'name': self.name} @classmethod def find_by_teacher_id(cls, teacher_id): return cls.query.filter_by(teacher_id=teacher_id).all() @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).first() @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first()
class RestoreTask(db.Model): """ A task is a one restore. """ __tablename__ = 'restoretasks' id = db.Column(db.Integer, primary_key=True) # id started = db.Column(db.DateTime, default=datetime.datetime.utcnow) # start time ended = db.Column(db.DateTime) # end time backupname = db.Column(db.String) # name of the new vm backup_id = db.Column(db.Integer, db.ForeignKey('backups.id')) # backup id backup = db.relationship('Backup', lazy='immediate') # backup object host_id = db.Column(db.Integer) # host id to restore to sr = db.Column(db.String) # sr to upload disk to pct1 = db.Column(db.Float) # first percentage (0 to 1) pct2 = db.Column(db.Float) # second percentage (0 to 1) divisor = db.Column(db.Float) # division of percentage (0 to 1) message = db.Column(db.String) # status of the task status = db.Column(db.String) # status of the task def pct(self): if self.pct1 == None: s1 = 0 else: s1 = self.pct1 if self.pct2 == None: s2 = 0 else: s2 = self.pct1 if self.divisor == None: d = 1 else: d = self.divisor return s1 * d + s2 * (1 - d)
class Image(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String()) digest = db.Column(db.String()) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) created_on = db.Column(db.DateTime, default=datetime.utcnow) output = db.Column(db.Float) def __init__(self, name, f, user): self.name = name self.user = user self.digest = hash_file(f) self.output = Image.analyze(f) @property def url(self): return generate_url( config.S3_BUCKET, self.digest, config.S3_URL_EXPIRATION, ) @property def dict(self): return { "id": self.id, "digest": self.digest, "name": self.name, "url": self.url, "output": self.output, "created_on": timestamp(self.created_on), } @staticmethod def analyze(f): """ Given a file object, analyze and return value """ return random.uniform(0, 12)
class StudentModel(db.Model): __tablename__ = 'students' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255)) school_id = db.Column(db.Integer, db.ForeignKey('schools.id')) school = db.relationship('SchoolModel') def __init__(self, _id: int, name: str, school_id: int = None): self.id = _id self.name = name self.school_id = school_id # Memformat data kedalam format JSON def _json(self): return {'id': self.id, 'name': self.name} # Menampilkan semua data @classmethod def get(cls): return cls.query.order_by(cls.name).all() # Menampilkan data berdasarkan id @classmethod def find(cls, id: int): return cls.query.filter_by(id=id).first() # Menyimpan data (Insert & Update) def save(self): db.session.add(self) db.session.commit() return None # Menghapus data berdasarkan id @classmethod def delete(cls, id: int): cls.query.filter_by(id=id).delete() db.session.commit() return None
class StatusCategoryStatusMapping(db.Model): __tablename__ = "status_category_status_mappings" id = db.Column(db.Integer, primary_key=True, nullable=False) activity_id = db.Column(db.Integer, db.ForeignKey("activities.activity_id"), nullable=True) status = db.Column(db.String, nullable=False) status_category = db.Column(db.Enum(StatusCategory), nullable=False) activity = db.relationship("Activity", backref="status_mappings") __table_args__ = ( db.UniqueConstraint("activity_id", "status"), db.Index( "ix_status_activity_id_null", "status", unique=True, postgresql_where=(activity_id.is_(None)), ), )
class Category(db.Model): __tablename__ = "category" id = db.Column(db.String(36), default=lambda: str(uuid4()), primary_key=True) name = db.Column(db.String(80), nullable=False) description = db.Column(db.String(240), nullable=False) product_id = db.Column(db.String(36), db.ForeignKey("product.id")) product = db.relationship(Product, back_populates="categories") @validates('name') def name_validate(self, key, name: str): if not name: raise ConflictException(msg='Category name is empty') return name @validates('description') def description_validate(self, key, description: str): if not description: raise ConflictException(msg='Category description is empty') return description
class Currency(db.Model): """Currency model. Parameters ---------- db : Model """ __tablename__ = 'currency' id = db.Column(db.Integer, primary_key=True) symbol = db.Column(db.String(3)) description = db.Column(db.String(64)) company_id = db.Column( db.Integer, db.ForeignKey('organization.id') ) company = db.relationship( 'Company', backref='currencies' )
class Assignment(db.Model): """Assignment model Parameters ---------- db : Model """ __tablename__ = 'assignment' id = db.Column(db.Integer, primary_key=True) starts = db.Column(db.DateTime) ends = db.Column(db.DateTime) # resource_id = db.Column(db.Integer, db.ForeignKey('resource.id')) # resource = db.relationship('Resource', backref='assignments') # job_task_id = db.Column(db.Integer, db.ForeignKey('job_task.id')) # job_task = db.relationship('JobTask', backref='assignments') assignment_status_id = db.Column(db.Integer, db.ForeignKey('assignment_status.id'))
class Address(db.Model): __tablename__ = 'address' id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid4())) street = db.Column(db.String(150)) zipcode = db.Column(db.String(8)) neighborhood = db.Column(db.String(60)) number = db.Column(db.String(20)) city = db.Column(db.String(80)) state = db.Column(db.String(80)) country = db.Column(db.String(80)) complement = db.Column(db.String(80)) provider_id = db.Column(db.String, db.ForeignKey('provider.id'), nullable=False, index=True) providers = db.relationship('Provider', backref='addresses', foreign_keys=[provider_id]) def __init__(self, **kwargs): super().__init__(**kwargs) for keys in kwargs: if kwargs[keys] is None or kwargs[keys] == '': raise NullOrNoneValueException() def serialize(self) -> dict: return { "id": self.id, "street": self.street, "zipcode": self.zipcode, "neighborhood": self.neighborhood, "number": self.number, "city": self.city, "state": self.state, "country": self.country, "complement": self.complement }
class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80), nullable=False) body = db.Column(db.Text, nullable=False) pub_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) author = db.Column(db.String(80), nullable=False) tags = db.relationship('Tag', secondary=tags, lazy='subquery', backref=db.backref('posts', lazy=True)) category_id = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=False) category = db.relationship('Category', backref=db.backref('posts', lazy=True)) def __repr__(self): return '<Post %r>' % self.title def __str__(self): return self.title
class Citizen(db.Model): """ Основной класс жителя. Primary Key является составным и зависит от citizen_id и dataset_id. """ citizen_id = db.Column(db.Integer, primary_key=True) town = db.Column(db.String) street = db.Column(db.String) building = db.Column(db.String) apartment = db.Column(db.Integer) name = db.Column(db.String) birth_date = db.Column(db.String) gender = db.Column(db.String) relatives = db.Column(db.String) dataset_id = db.Column(db.Integer, db.ForeignKey('dataset.id'), primary_key=True) # Создаём двухстороннюю ссылку на конкретную выгрузку (dataset) dataset = db.relationship('Dataset', backref=db.backref('citizens')) def get_relatives_list(self): return unpack_relatives_to_int_list(self.relatives) def json_representation(self): relatives_list = self.get_relatives_list() res = { "citizen_id": self.citizen_id, "town": self.town, "street": self.street, "building": self.building, "apartment": self.apartment, "name": self.name, "birth_date": self.birth_date, "gender": self.gender, "relatives": relatives_list } return res def __repr__(self): return 'Citizen %r cit_id %r' % (self.dataset, self.citizen_id)
class PDB(db.Model): # __tablename__ = 'pdb' id = db.Column(db.Integer, primary_key=True) pdb_id = db.Column(db.String(64), unique=True) in_bindingdb_validation_set = db.Column(db.Boolean) #ligand column may not be necessary ligand = db.Column(db.String(64)) expressed_in_ecoli = db.Column(db.Boolean) expression_system = db.Column(db.String(64)) #SEQRES sequence sequence = db.Column(db.String(1024), unique=True) method = db.Column(db.String(64), unique=True) uniprot_id = db.Column(db.Integer, db.ForeignKey('uniprot.id')) # uniprot_acc = db.Column(db.String(64), db.ForeignKey('uniprot.acc')) hets = db.relationship("HET", backref='pdb', lazy='dynamic') # def __init__(self, pdb_id, present_in_BindingDB_validation_set): # self.pdb_id = pdb_id # self.present_in_BindingDB_validation_set = present_in_BindingDB_validation_set def __repr__(self): return "<PDB %r>" % self.pdb_id
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 @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_in_database(self): db.session.add(self) db.session.commit() def delete_from_database(self): db.session.delete(self) db.session.commit() def json(self): return { 'id': self.id, 'name': self.name, 'price': self.price, 'store': self.store_id }
class Post(db.Model): __tablename__ = "t_post" id = db.Column(db.Integer, primary_key=True, autoincrement=True) post_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) poster_id = db.Column(db.Text()) poster_name = db.Column(db.Text()) post_contents = db.Column(db.Text()) parent_post_id = db.Column(db.Integer) ke_id = db.Column(db.Integer, db.ForeignKey('m_thread.id')) password = db.Column(db.Text()) is_delete = db.Column(db.Integer) def __init__(self, post_time, poster_id, poster_name, post_contents, parent_post_id, ke_id, password, is_delete): self.post_time = post_time self.poster_id = poster_id self.poster_name = poster_name self.post_contents = post_contents self.parent_post_id = parent_post_id self.ke_id = ke_id self.password = password self.is_delete = is_delete
class AccessRequest(db.Model): """Class that represent access_request table in DB. Used to store information when someone requires a token.""" __tablename__ = "access_requests" id = db.Column(db.Integer, primary_key=True) _center_id = db.Column('center_id', db.Integer, db.ForeignKey("centers.id")) timestamp = db.Column(db.TIMESTAMP) def __init__(self, center_id): self.center_id = center_id self.timestamp = datetime.now() @property def center_id(self): return self._center_id @center_id.setter def center_id(self, value): if not isinstance(value, int) or type(value) is not int: raise TypeError('center_id must be a int') self._center_id = value @staticmethod def json(ac): """Converts given AccessRequest object to json formatted data""" return {'id': ac.id, 'center_id': ac.center_id, 'timestamp': ac.timestamp} @staticmethod def get_all_access_requests(): """Get all rows from table access_request""" return [AccessRequest.json(ac) for ac in AccessRequest.query.all()] @staticmethod def add_access_request(_center_id): """Adds new access request to DB""" new_access_request = AccessRequest(_center_id) db.session.add(new_access_request) db.session.commit()
class ToDoItem(db.Model): __tablename__ = 'todo_item' id = db.Column(db.Integer, primary_key=True) content = db.Column(db.String(255)) # 255 characters created = db.Column(db.DateTime, nullable=True, default=datetime.utcnow) due_date = db.Column(db.DateTime, nullable=True) done_flag = db.Column(db.Boolean, default=False # db.Boolean.create_constraint=False ) todo_list_id = db.Column( db.Integer, db.ForeignKey('todo_list.id'), # todo_list (table name). id (field) nullable=False) todo_list = db.relationship( 'ToDoList', backref=db.backref( 'todos', lazy=True, cascade='all, delete-orphan') # si no es lazy da error ) def serialize(self): if self.__getattribute__('due_date'): return { 'id': self.id, 'content': self.content, 'created': self.created.strftime('%d, %b, %Y'), 'due_date': self.due_date.strftime('%d, %b, %Y'), 'done_flag': self.done_flag, 'todo_list_id': self.todo_list_id } else: return { 'id': self.id, 'content': self.content, 'created': self.created.strftime('%d, %b, %Y'), 'done_flag': self.done_flag, 'todo_list_id': self.todo_list_id }
class CategoryLine(db.Model): __tablename__ = 'category_lines' id = db.Column(db.String(36), default=lambda: str(uuid4()), primary_key=True) active = db.Column(db.Boolean(), default=True) category_line = db.Column(db.String(100), unique=True, nullable=False) category = db.relationship(Category) profit_percentage = db.Column(db.Float(), nullable=False) category_id = db.Column(db.String(36), db.ForeignKey(Category.id), nullable=False) on_create = db.Column(db.DateTime, default=datetime.datetime.now) on_update = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now) def serialize(self) -> Dict[str, Union[bool, str]]: return { 'id': self.id, 'active': self.active, 'profit_percentage': self.profit_percentage, 'category_line': self.category_line, 'category_id': self.category_id, 'on_create': self.on_create, 'on_update': self.on_update } def __init__(self, **kwargs): super().__init__(**kwargs) validating_empty_fields([], **kwargs) validating_if_field_is_not_str( ['active', 'on_create', 'on_update', 'profit_percentage'], **kwargs) validating_if_field_is_bool(['active'], **kwargs) validating_if_field_is_float(['profit_percentage'], **kwargs) validating_size_of_fields(**kwargs)
class ItemModel(db.Model): __tablename__ = 'items' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) #max chars allowed = 80 price = db.Column(db.Float(precision=2)) store_id = db.Column( db.Integer, db.ForeignKey('stores.id')) #id from stores table is foreign key store = db.relationship( 'StoreModel' ) #So now every item model has a store model that matches the store_id. #db.relationship automatically finds this store using a join def __init__(self, name, price, store_id): self.name = name #these self var names should be same as the table columns. #The init method will be called for all rows, i.e. objects for all rows will be made by sqlalchemy 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): return cls.query.filter_by(name=name).first( ) #A method of SQLAlchemy model that automatically connects to database #and basically does the query SELECT * FROM __tablename__ WHERE name = name LIMIT 1 i.e. 1st matching element #then converts the resulting row into ItemModel object and returns def save_to_db(self): #insert and update both db.session.add(self) #adds/updates the self class as row 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) -> 'ItemModel': # SELECT * FROM __tablename__ WHERE name=name LIMIT 1 return cls.query.filter_by(name=name).first() @classmethod def find_all(cls) -> List['ItemModel']: # SELECT * FROM __tablename__ return cls.query.all() def save_to_db(self): # INSERT INTO __tablename__ VALUES (NULL, ?, ?) # UPDATE __tablename__ SET price=? WHERE name=? db.session.add(self) db.session.commit() def delete_from_db(self): # DELETE FROM __tablename__ WHERE name=? db.session.delete(self) db.session.commit()
class Post(db.Model): __tablename__ = 'posts' id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid.uuid4())) user_id = db.Column(db.String(36), db.ForeignKey('users.id')) title = db.Column(db.String(50), nullable=False) text = db.Column(db.Text(), nullable=False) created_at = db.Column(db.DateTime(timezone=True), server_default=func.now()) updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now()) user = db.relationship('User', back_populates='posts', uselist=False) categories = db.relationship('Category', secondary=posts_categories) def serialize(self, detail=False): author = "{} {}".format(self.user.profile.first_name, self.user.profile.last_name) response = { 'id': self.id, 'author': author, 'title': self.title, 'text': self.text } if detail: categories_list = [ category.serialize() for category in self.categories ] response.update({'categories': categories_list}) return response
class ItemModel(db.Model): __tablename__ = 'items' id = db.Column(db.Integer, autoincrement=True, primary_key=True) name = db.Column(db.String(80)) price = db.Column(db.Float(precision=2)) # creating additional column to connect Item and Store tables store_id = db.Column(db.Integer, db.ForeignKey('stores.id')) store = db.relationship('StoreModel') # to contain object properties of internal method def __init__(self, name, price, store_id): 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): return cls.query.filter_by( name=name).first() # Select * from items where name = name LIMIT 1 @classmethod def find_by(cls): return cls.query.all() # this will insert and update into DB 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 Address(db.Model): __tablename__ = 'address' id = db.Column(db.Integer, autoincrement=True, primary_key=True, nullable=False) name = db.Column(db.String(50), nullable=False, default='') postal_code = db.Column(db.String(20), nullable=False, default='') province_name = db.Column(db.String(50), nullable=False, default='') city_name = db.Column(db.String(50), nullable=False, default='') county_name = db.Column(db.String(50), nullable=False, default='') detail_info = db.Column(db.String(200), nullable=False, default='') national_code = db.Column(db.String(20), nullable=False, default='') tel_number = db.Column(db.String(30), nullable=False, default='') uid = db.Column(db.Integer, db.ForeignKey('member.id')) def __repr__(self): return "<Model Address `{}`>".format(self.name) def __str__(self): return self.name + ' ' \ + self.province_name + ' ' + self.city_name + ' ' + self.county_name + ' ' + self.detail_info + ' ' \ + self.tel_number
class Note(db.Model): id = db.Column("id", db.Integer, primary_key=True) title = db.Column("title", db.String(200)) text = db.Column("text", db.String(100)) date = db.Column("date", db.String(50)) last_modified = db.Column("last_modified", db.String(50)) is_favorite = db.Column("is_favorite", db.Boolean()) is_published = db.Column("is_published", db.Boolean()) # can create a foreign key; referencing the id variable in the User class, so that is why it is lowercase u user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False) comments = db.relationship("Comment", backref="note", cascade="all, delete-orphan", lazy=True) def __init__(self, title, text, date, user_id): self.title = title self.text = text self.date = date self.last_modified = date self.user_id = user_id self.is_favorite = False self.is_published = False
class Sensor(db.Model, SerializerMixin): __tablename__ = 'sensor' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), unique=True) land_id = db.Column(db.Integer, db.ForeignKey('land.id')) status = db.Column(db.Boolean, default=True) battery = db.Column(db.Float) temperature = db.Column(db.Float) signal_strength = db.Column(db.Integer) float = db.Column(db.Boolean) address = db.Column(db.String(100), unique=True) last_update = db.Column(db.DateTime) notes = db.Column(db.String(100), default='') trip_time = db.Column(db.DateTime) serialize_rules = ('-sensor_configs.sensor', ) sensor_configs = db.relationship("SensorConfig", backref='sensor', cascade='all,delete') def __str__(self): return f'Name: {self.name}: address: {self.address}'
class Office(db.Model): __tablename__ = 'office' id = db.Column(db.Integer, primary_key=True) cp_id = db.Column(db.String(10), db.ForeignKey('congressperson.id'), nullable=False) city = db.Column(db.String(100), nullable=False) phone = db.Column(db.String(10), nullable=True) info_json = db.Column(db.String(2048), nullable=True) __table_args__ = (db.UniqueConstraint("cp_id", "city"), ) @property def info(self): try: self.__info except AttributeError: self.__info = json.loads(self.info_json) return self.__info @info.setter def info(self, info): self.__info = info self.info_json = json.dumps(self.__info)