class CustomerModel(db.Model): __tablename__ = 'customer' customer_id = db.Column(db.Integer, primary_key=True, autoincrement=True) password = db.Column(db.String(30), nullable=False) full_name = db.Column(db.String(30), nullable=False) address = db.Column(db.String(30), nullable=False) gender = db.Column(db.Enum("M", "F"), nullable=False) marital_status = db.Column(db.Enum("S", "M", "W"), nullable=False) customer_type = db.Column(db.Enum("H", "A", "B"), nullable=False) def __init__(self, customer_id, password, full_name, address, gender, marital_status, customer_type): self.customer_id = customer_id self.full_name = full_name self.password = password self.address = address self.gender = gender self.marital_status = marital_status self.customer_type = customer_type def json(self): return { 'customer_id': self.customer_id, 'full_name': self.full_name, 'password': self.password, 'address': self.address, 'gender': self.gender, 'marital_status': self.marital_status, 'customer_type': self.customer_type } @classmethod def find_all(cls): return cls.query.all() @classmethod def find_by_username(cls, username): return cls.query.filter_by(full_name=username).first() @classmethod def find_by_id(cls, _id): return cls.query.filter_by(customer_id=_id).first() def save_to_db(self): self.password = md5(self.password.encode("utf-8")).hexdigest() print(self.password) db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class Map(db.Model): __tablename__ = 'map' id = db.Column(db.Integer, primary_key=True) created = db.Column(db.Float, default=time.time, index=True) name = db.Column(db.String, nullable=False, index=True) is_tiles = db.Column(db.Boolean, default=False) status = db.Column(db.Enum("new", "ready", "deleted", name="map_status_enum"), nullable=False, default="new") loc_1_lat = db.Column(db.Float) loc_1_lon = db.Column(db.Float) loc_1_x = db.Column(db.Float) loc_1_y = db.Column(db.Float) loc_2_lat = db.Column(db.Float) loc_2_lon = db.Column(db.Float) loc_2_x = db.Column(db.Float) loc_2_y = db.Column(db.Float) loc_3_lat = db.Column(db.Float) loc_3_lon = db.Column(db.Float) loc_3_x = db.Column(db.Float) loc_3_y = db.Column(db.Float) group = db.Column(db.Integer, db.ForeignKey("group.id"), nullable=False) def __init__(self, name): self.name = name
class TelephoneModel(db.Model): __tablename__ = 'TELEPHONE' number = db.Column('number', db.String(15), primary_key=True) telephone_type = db.Column('type', db.Enum(TelephoneTypeEnum), nullable=False) tel_person_id = db.Column('id_person', db.Integer, db.ForeignKey('PERSON.id_person')) def __init__(self, number, telephone_type, tel_person_id): self.number = number self.telephone_type = telephone_type self.tel_person_id = tel_person_id def json(self): return { 'number': self.number, 'telephone_type': self.telephone_type.value } @classmethod def find_by_number(cls, number): return cls.query.filter_by(number=number).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 ArtistModel(db.Model): __tablename__ = 'artists' #This is table name id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30), unique=True, nullable=False) country = db.Column(db.String(30), nullable=False) genre = db.Column(db.Enum(*genres, name='genres_types'), nullable=False) def __init__(self, name, country, genre): self.name = name self.country = country self.genre = genre def json(self): return { "id": self.id, "name": self.name, "country": self.country, "genre": self.genre } def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit() @classmethod def find_by_id(cls, id): return cls.query.filter_by(id=id).first()
class OrderEntity(db.Model): __tablename__ = "order" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False, unique=True) latitude = db.Column(db.Float, nullable=False) longitude = db.Column(db.Float, nullable=False) status = db.Column(db.Enum(OrderStatus), nullable=False) time_zone = db.Column(db.String, nullable=False) comments = db.Column(db.String, nullable=True) total = db.Column(db.BigInteger, nullable=True) created_at = db.Column(db.DateTime, nullable=True, server_default=db.func.current_timestamp()) updated_at = db.Column(db.DateTime, nullable=True, server_onupdate=db.func.current_timestamp()) scheduled_at = db.Column(db.DateTime, nullable=True) finished_at = db.Column(db.DateTime, nullable=True) deleted = db.Column(db.DateTime, nullable=False, default=False) @classmethod def save(cls) -> None: db.session.add(cls) db.session.commit() @classmethod def delete(cls) -> None: db.session.delete(cls) db.session.commit()
class TestTaskModel(db.Model): __bind_key__ = 'qms' __tablename__ = 'qa_testtask' id = db.Column(db.Integer, autoincrement=True, primary_key=True) name = db.Column(db.String(90)) product = db.Column( db.Enum('eWordIMCIS', 'eWordRIS', 'eWordToken', 'eWordUniversal', '医学影像浏览器', '发片工作站', '影像存档与通信系统', '按需打印', '研发管理系统', '自动化测试平台V2')) project = db.Column(db.String(90)) build_man = db.Column(db.String(90)) owner = db.Column(db.String(90)) smokeresult = db.Column(db.Enum('pass', 'fail')) reason = db.Column(db.String(1024)) perpetrators = db.Column(db.String(90)) tester = db.Column(db.String(90)) starttime = db.Column(db.DateTime) finishedtime = db.Column(db.DateTime) def __init__(self, name, product, project, build_man, owner, smokeresult, reason, perpetrators, tester, starttime, finishedtime): self.name = name self.product = product self.project = project self.build_man = build_man self.owner = owner self.smokeresult = smokeresult self.reason = reason self.perpetrators = perpetrators self.tester = tester self.starttime = starttime self.finishedtime = finishedtime # 获取冒烟测试列表 @classmethod def query_all(cls): return cls.query.all() # 提交到数据库 def add_to_db(self): try: db.session.add(self) db.session.commit() except: db.session.rollback() db.session.flush()
class BloodBag(db.Model): __tablename__ = "blood_bags" id = db.Column(db.Integer, primary_key=True, autoincrement=True) blood_bank_id = db.Column(db.Integer, db.ForeignKey('blood_banks.id'), nullable=False) bag_size_id = db.Column(db.Integer, db.ForeignKey('bag_sizes.id'), nullable=False) blood_group = db.Column(db.Enum(BloodGroupType), nullable=False) quantity = db.Column(db.Integer, default=0, nullable=False) collection_date = db.Column(db.DateTime, default=datetime.utcnow, nullable=False) expiry_date = db.Column(db.DateTime, nullable=False) # blood_bank = db.relationship('BloodBag', backref=db.backref('blood_bags', lazy='dynamic')) # bag_size = db.relationship("BagSize", foreign_keys=[bag_size_id], lazy='dynamic') def total_ml(self) -> int: return self.size.volume * self.quantity @classmethod def find_all(cls): return cls.query.all() @classmethod def find_all_by_bank(cls, bank_id: int) -> List['BloodBag']: return cls.query.filter_by(blood_bank_id=bank_id).all() @classmethod def find_all_by_bank_and_group(cls, bank_id: int, group: int) -> List['BloodBag']: blood_group = BloodGroupType(group) query = cls.query.filter_by(blood_bank_id=bank_id, blood_group=blood_group) return query.all() @classmethod def find_by_bank_group_size(cls, bank_id: int, group: int, size_id: int) -> 'BloodBag': blood_group = BloodGroupType(group) query = cls.query.filter_by(blood_bank_id=bank_id, blood_group=blood_group, bag_size_id=size_id) return query.first() def save_to_db(self) -> None: db.session.add(self) db.session.commit() def delete_from_db(self) -> None: db.session.delete(self) db.session.commit() def __repr__(self): return f"{self.blood_bank_id} has {self.quantity} bags of \
class Event(db.Model): __tablename__ = 'event' id = db.Column(UUID(as_uuid=True), primary_key=True, server_default=db.text("uuid_generate_v4()")) item = db.Column(UUID(as_uuid=True), db.ForeignKey('moveout.id'), nullable=False) detail = db.Column(db.String(200), unique=False, nullable=False) type = db.Column(db.Enum(EventType), unique=False, nullable=False) created_date = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now()) @classmethod def find_by_id(cls, event_id): return cls.query.filter_by(id=event_id).first() @classmethod def find_by_item_id(cls, item_id): return cls.query.filter_by(item=item_id).all() @classmethod def find_total_by_type(cls): return { 'unknown': cls.query.filter_by(type=EventType.UNKNOWN).count(), 'external': cls.query.filter_by(type=EventType.EXTERNAL).count(), 'staff': cls.query.filter_by(type=EventType.STAFF).count(), 'user': cls.query.filter_by(type=EventType.USER).count(), 'system': cls.query.filter_by(type=EventType.SYSTEM).count() } @classmethod def find_oldest_event(cls): return cls.query.order_by(cls.created_date.asc()).first() @classmethod def find_newest_event(cls): return cls.query.order_by(cls.created_date.desc()).first() @classmethod def find_all_events(cls, filter_params): query = cls.query if filter_params['sort'] == OrderType.ASCENDING: query = query.order_by(cls.created_date.asc()) elif filter_params['sort'] == OrderType.DESCENDING: query = query.order_by(cls.created_date.desc()) return query.all() def commit(self): db.session.add(self) db.session.commit() def remove(self): db.session.delete(self) db.session.commit()
class Equipment_log(db.Model): __tablename__ = 'equipment_log' id = db.Column(db.Integer, primary_key=True, autoincrement=True) create_time = db.Column(db.DateTime, nullable=False, default=datetime.now) status = db.Column(db.Enum('正常', '异常'), server_default='正常') equipment_id = db.Column(db.Integer, db.ForeignKey('equipment.id')) equipment = db.relationship('Equipment', backref=db.backref('equipment_logs'))
class Test(db.Model): __tablename__ = 'tests' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False, unique=True) unit = db.Column(db.String(255), nullable=False) type = db.Column(db.Enum('oak', 'bak'), nullable=True) normal_values = db.relationship('TestNormalValue')
class TestNormalValue(db.Model): __tablename__ = 'tests_normal_values' id = db.Column(db.Integer, primary_key=True) test_id = db.Column(db.ForeignKey('tests.id'), nullable=False, index=True) patient_category = db.Column(db.Enum('all', 'child', 'male', 'female'), nullable=False) min = db.Column('min', db.Float, nullable=False) max = db.Column('max', db.Float, nullable=False)
class ArtistModel(db.Model): __tablename__ = 'artist' #This is table name id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30), unique=True, nullable=False) country = db.Column(db.String(30), nullable=False) genre = db.Column(db.Enum(*genres, name='genres_types'), nullable=False) events = db.relationship('EventModel', secondary=artist_events, backref=db.backref('artists', lazy='dynamic')) def __str__(self): return str(self.id) + self.name + self.country def json(self): return { "id": self.id, "name": self.name, "country": self.country, "genre": self.genre } @classmethod def find_by_id(cls, id): if id: return ArtistModel.query.get(id) else: return None @classmethod def find_by_name(cls, name): if name: return ArtistModel.query.filter_by(name=name).first() else: return None @classmethod def find_all(cls): return ArtistModel.query.all() def save_to_db(self): if self.id and ArtistModel.query.get(self.id): db.session.commit() else: db.session.add(self) db.session.commit() def delete_from_db(self): if self.id and ArtistModel.query.get(self.id): db.session.delete(self) db.session.commit() else: raise Exception("Warning not in DB") def __init__(self, name, country, genre): self.name = name self.country = country self.genre = genre
class ArtistModel(db.Model): __tablename__ = n.ARTS #This is table name id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(30), unique=True, nullable=False) country = db.Column(db.String(30), nullable=False) genre = db.Column(db.Enum(*genres, name='genres_types'), nullable=False) def __init__(self, name, country, genre): self.name = name self.country = country self.genre = genre def json(self): return { n.ART: { n.ID: self.id, n.NM: self.name, n.CTRY: self.country, n.GNR: self.genre } } def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit() def modify_from_db(self, name, country, genre): self.name = name self.country = country self.genre = genre db.session.add(self) db.session.commit() @classmethod def find_by_id(cls, aid): return ArtistModel.query.filter_by(id=aid).first() @classmethod def find_by_name(cls, aname): return ArtistModel.query.filter_by(name=aname).first() @classmethod def find_by_country(cls, acountry): return ArtistModel.query.filter_by(country=acountry).all() @classmethod def find_by_genre(cls, agenre): return ArtistModel.query.filter_by(genre=agenre).all() @classmethod def return_all(cls): return {n.ARTS: [a.json()[n.ART] for a in ArtistModel.query.all()]}
class Equipment(db.Model): __tablename__ = 'equipment' id = db.Column(db.Integer, primary_key=True, autoincrement=True) gaode_longitude = db.Column(db.DECIMAL(precision='15,6')) gaode_latitude = db.Column(db.DECIMAL(precision='15,6')) status = db.Column(db.Enum('正常', '故障'), server_default='正常') # 设备状态 location = db.Column(db.String(100)) admin_id = db.Column(db.Integer, db.ForeignKey('admin_people.id')) # 仪器管理者id admin = db.relationship('Admin_people', backref=db.backref('equipments'))
class TestTaskModel(db.Model): __bind_key__ = 'zentao' __tablename__ = 'zt_testtask' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(90)) product = db.Column(db.Integer) project = db.Column(db.Integer) build = db.Column(db.String(30)) owner = db.Column(db.String(30)) begin = db.Column(db.Date) end = db.Column(db.Date) status = db.Column(db.Enum('blocked', 'doing', 'wait', 'done')) deleted = db.Column(db.Enum('0', '1')) # 通过id获取测试单列表 @classmethod def query_by_id(cls, _id): return cls.query.filter_by(id=_id, deleted='0').first()
class User_log(db.Model): __tablename__ = 'user_log' id = db.Column(db.Integer, primary_key=True, autoincrement=True) # 这里的id是每检测一个学生就会有一个id temperature = db.Column(db.String(100)) create_time = db.Column(db.DateTime, default=datetime.now) # 检测时间 status = db.Column(db.Enum('正常', '异常'), server_default='正常') if_sure = db.Column(db.BOOLEAN,default=False) # 记录是否经过确认 equipment_id = db.Column(db.Integer, db.ForeignKey('equipment.id'), nullable=False) # 检测的仪器 user_id = db.Column(db.Integer, db.ForeignKey('user.id')) # 后期查找时通过user_id来找到多次检测的信息 user = db.relationship('User', backref=db.backref('user_logs')) equipment = db.relationship('Equipment', backref=db.backref('user_logs1'))
class TestReportModel(db.Model): __bind_key__ = 'zentao' __tablename__ = 'zt_testreport' id = db.Column(db.Integer, primary_key=True) product = db.Column(db.Integer) project = db.Column(db.Integer) tasks = db.Column(db.String(255)) # 测试单号 build = db.Column(db.String(255)) # 版本 title = db.Column(db.String(255)) # 标题 createBy = db.Column(db.String(30)) # 创建人 deleted = db.Column(db.Enum('0', '1'))
class TitleModel(db.Model): __tablename__ = 'titles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) path = db.Column(db.String, unique=True) title_type = db.Column(db.Enum(TitleType), default=TitleType.unkonwn) file_size = db.Column(db.BigInteger) duration = db.Column(db.Integer) video_codec = db.Column(db.String) video_encoding_settings = db.Column(db.String) height = db.Column(db.Integer) width = db.Column(db.Integer) writing_application = db.Column(db.String) time_added = db.Column(db.DateTime, default=current_time) time_modified = db.Column(db.DateTime) time_updated = db.Column(db.DateTime, default=current_time, onupdate=current_time) movie_id = db.Column(db.Integer, db.ForeignKey('movies.id', ondelete='CASCADE'), nullable=True) movie = db.relationship('MovieModel', backref='titles') disc_id = db.Column(db.Integer, db.ForeignKey('discs.id', ondelete='CASCADE'), nullable=True) disc = db.relationship('DiscModel', backref='titles') @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first() @classmethod def find_by_path(cls, path): return cls.query.filter_by(path=path).first() @classmethod def search(cls, params): q = db.session.query(cls) for key, value in params.items(): # Perform an exact match for columns that require it if key == 'id' or key == 'title_type': q = q.filter(getattr(cls, key) == value) # Perform a like query for everything else else: q = q.filter(getattr(cls, key).like("%%{}%%".format(value))) return q.all() def save_to_db(self): db.session.add(self) db.session.commit()
class Race_control(db.Model): __tablename__ = 'race_control' id = db.Column(db.Integer, primary_key=True) lat = db.Column(db.Float) lon = db.Column(db.Float) order = db.Column(db.Integer) label = db.Column(db.String) type = db.Column(db.Enum("start", "control", "finish", name="race_control_enum"), nullable=False, default="control")
class MessageThread(db.Model): __tablename__ = "message_thread" id = db.Column(db.BigInteger, primary_key=True) subject = db.Column(db.String(255), nullable=False) from_user_id = db.Column(db.BigInteger, index=True) to_user_id = db.Column(db.BigInteger, index=True) message_type = db.Column(db.Enum("STOK", "PRODUK", "COMPLAINT"), default="PRODUK") created_at = db.Column(db.DateTime, default=datetime.datetime.now()) updated_at = db.Column(db.DateTime, default=datetime.datetime.now()) deleted_at = db.Column(db.DateTime, nullable=True)
class CategoryModel(db.Model): __tablename__ = "categories" id = db.Column(db.Integer, primary_key=True) percentage = db.Column(db.Float(precision=2), default=0.0) tags = db.Column(db.Enum(Tags)) total = db.Column(db.Float(precision=2)) remaining = db.Column(db.Float(precision=2)) items = db.relationship('ItemModel', lazy="dynamic") user_id = db.Column(db.Integer, db.ForeignKey('users.id')) user = db.relationship('UserModel') def __init__(self, percentage, tags, total, remaining, user_id): self.percentage = percentage self.tags = tags self.total = total self.remaining = remaining self.user_id = user_id # def json(self): # return { 'id': self.id,'name': self.name} # @classmethod # def find_by_id(cls, id): # new_store = cls.query.filter_by(id = id).first() # This is returning a StoreModel object SELECT * FROM stores WHERE id = id # return new_store.json() @classmethod def find_by_id(cls, user_id, id): user = UserModel.find_by_id(user_id) return cls.query.filter_by(user_id=user.id, id=id).first( ) # This is returning a StoreModel object SELECT * FROM stores WHERE name = name # @classmethod # def find_by_name(cls, name): # return cls.query.filter_by(name = name).first() # This is returning a StoreModel object SELECT * FROM stores WHERE name = name @classmethod def find_by_tag(cls, tag): return cls.query.filter_by( tags=tag ) # This is returning a StoreModel object SELECT * FROM stores WHERE tag = tag 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 Sample(db.Model): __tablename__ = 'samples' id = db.Column(db.Integer, primary_key=True) type = db.Column(db.Enum('cbc', 'cmp', 'other'), nullable=False) date = db.Column(db.Date, nullable=False) patient_id = db.Column(db.ForeignKey('patients.id'), nullable=False, index=True) department_id = db.Column(db.ForeignKey('departments.id'), nullable=False, index=True) department = db.relationship('Department') patient = db.relationship('Patient', back_populates='samples') results = db.relationship("SampleResult")
class UserConfirmation(db.Model): __tablename__ = 'user_confirmation' id = db.Column(db.Integer, primary_key=True) hash = db.Column(db.String, nullable=False) expires = db.Column(db.Integer, nullable=False) target = db.Column(db.Enum("email", "password", "account", name="user_confirmation_target_enum"), nullable=False) user = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False, index=True)
class AutoInsuranceModel(db.Model): __tablename__ = 'auto_insurance' customer_id = db.Column(db.Integer, db.ForeignKey('customer.customer_id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True) a_start_date = db.Column(db.Date, nullable=False) a_end_date = db.Column(db.Date, nullable=False) a_premium_amount = db.Column(db.DECIMAL(12, 2), nullable=False) a_policy_status = db.Column(db.Enum("C", "P")) customer = db.relationship('CustomerModel') def __init__(self, customer_id, a_start_date, a_end_date, a_premium_amount, a_policy_status): self.customer_id = customer_id self.a_start_date = a_start_date self.a_end_date = a_end_date self.a_premium_amount = a_premium_amount self.a_policy_status = a_policy_status def json(self): return { 'a_customer_id': self.a_customer_id, 'a_start_data': self.a_start_date, 'a_end_date': self.a_end_date, 'a_premium_amount': self.a_premium_amount, 'a_policy_status': self.a_policy_status } @classmethod def find_by_id(cls, _id): return cls.query.filter_by(customer_id=_id).first() @classmethod def find_all(cls): return cls.query.all() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class HInsPaymentModel(db.Model): __tablename__ = 'h_ins_payment' h_payment_id = db.Column(db.Integer, primary_key=True) h_pay_amount = db.Column(db.DECIMAL(12, 2), nullable=False) h_payment_date = db.Column(db.Date, nullable=False) h_payment_method = db.Column(db.Enum("Paypal", "Credit", "Debit", "Check"), nullable=False) h_invoice_id = db.Column( db.Integer, db.ForeignKey('home_invoice.h_invoice_id', ondelete='CASCADE', onupdate='CASCADE')) def __init__(self, h_pay_amount, h_payment_date, h_payment_method, h_invoice_id): self.h_pay_amount = h_pay_amount self.h_payment_date = h_payment_date self.h_payment_method = h_payment_method self.h_invoice_id = h_invoice_id def json(self): return { 'h_payment_id': self.h_payment_id, 'h_pay_amount': self.h_pay_amount, 'h_payment_date': self.h_payment_date, 'h_payment_method': self.h_payment_method, 'h_invoice_id': self.h_invoice_id } @classmethod def find_by_id(cls, _id): return cls.query.filter_by(h_payment_id=_id).first() @classmethod def find_all(cls): return cls.query.all() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class VehicleModel(db.Model): __tablename__ = 'vehicle' vehicle_id = db.Column(db.Integer, primary_key=True) vin = db.Column(db.String(12), nullable=False) model_year = db.Column(db.String(4), nullable=False) vehicle_status = db.Column(db.Enum("L", "F", "O"), nullable=False) customer_id = db.Column( db.Integer, db.ForeignKey('auto_insurance.customer_id', ondelete='CASCADE', onupdate='CASCADE')) def __init__(self, vin, model_year, vehicle_status, customer_id): self.vin = vin self.model_year = model_year self.vehicle_status = vehicle_status self.customer_id = customer_id def json(self): return { 'vehicle_id': self.vehicle_id, 'vin': self.vin, 'model_year': self.model_year, 'vehicle_status': self.vehicle_status, 'custome_id': self.customer_id } @classmethod def find_by_vin(cls, vin): return cls.query.filter_by(vin=vin).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 Trace(db.Model): __tablename__ = 'trace' id = db.Column(db.Integer, primary_key=True) # for user access runner_hash = db.Column(db.String, unique=True, index=True) # for runner access status = db.Column(db.Enum("new", "accept", "reject", name="trace_status_enum"), nullable=False, default="new") race = db.Column(db.Integer, db.ForeignKey("race.id")) runner_name = db.Column(db.String(64)) locations = db.relationship("TraceLocation", lazy="dynamic") def __init__(self, name, race): self.runner_name = name self.race = race self.runner_hash = randomize_hash()
class Order(db.Model): '''orders table''' __tablename__ = 'orders' id = db.Column(db.Integer, primary_key=True) status = db.Column(db.Enum(Status)) date = db.Column(db.DATETIME) customer_id = db.Column(db.Integer, db.ForeignKey('customers.id')) customer = db.relationship('Customer', back_populates='orders') products = db.relationship("OrderProduct", back_populates="order") def __init__(self, status, date, customer_id): self.date = date self.status = status self.customer_id = customer_id def json(self): order_product = self.products order_products = [] for op in order_product: order_products.append(int(op.product_id)) return { 'id': self.id, 'status': self.status._name_, 'date': self.date.strftime('%Y-%m-%d'), 'customer_id': self.customer_id, 'products': order_products } @classmethod def find_by_id(cls, _id): '''Find Order by ID and return Order Instance''' return cls.query.filter_by(id=_id).first() def save_to_db(self): '''Persist Order information in Database''' db.session.add(self) db.session.commit()
class Machine(db.Model): machine_id = db.Column(db.Integer, primary_key=True) hostname = db.Column(db.String) created_at = db.Column(db.DateTime) updated_at = db.Column(db.DateTime) # (TODO): consider using Postgres' INET[] type ip_addresses = db.Column(postgresql.ARRAY(db.String)) net_interfaces = db.Column(postgresql.ARRAY(db.String)) operating_system = db.Column(db.Enum(OperatingSystems)) disk = db.Column(db.Integer) ram = db.Column(db.Integer) cores = db.Column(db.Integer) manufacturer = db.Column(db.String) model = db.Column(db.String) machine_services = db.relationship('Service', secondary=machine_services, backref=db.backref('machines', cascade='all'), cascade='save-update, merge') def __init__(self, hostname, **kwargs): self.hostname = hostname self.created_at = datetime.utcnow() self.updated_at = datetime.utcnow() self.ip_addresses = kwargs.get('ip_addresses') self.net_interfaces = kwargs.get('net_interfaces') self.disk = kwargs.get('disk') self.ram = kwargs.get('ram') self.cores = kwargs.get('cores') self.manufacturer = kwargs.get('manufacturer') self.model = kwargs.get('model') def to_dict(self): return dict(machine_id=self.machine_id, hostname=self.hostname, ip_addresses=self.ip_addresses, net_interfaces=self.net_interfaces, disk=self.disk, ram=self.ram, cores=self.cores, services=[s.name for s in self.machine_services])
class Role(BaseModel): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) role_type = db.Column(db.Enum(RoleTypes)) description = db.Column(db.String(120), unique=False, nullable=False) def __repr__(self): return '<Role %r>' % self.name @classmethod def find_by_type(cls, role_type: RoleTypes): return cls.query.filter_by(role_type=role_type).first() def commit(self): db.session.add(self) db.session.commit() def remove(self): db.session.delete(self) db.session.commit()