class Order(db.Model, BaseMixin, ReprMixin): __repr_fields__ = ['id', 'customer_id'] edit_stock = db.Column(db.Boolean(), default=True) sub_total = db.Column(db.Float(precision=2), default=0, nullable=True) total = db.Column(db.Float(precision=2), default=0, nullable=True) amount_paid = db.Column(db.Float(precision=2), default=0, nullable=True) auto_discount = db.Column(db.Float(precision=2), default=0, nullable=True) customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'), nullable=True) address_id = db.Column(db.Integer, db.ForeignKey('address.id'), nullable=True) retail_shop_id = db.Column(db.Integer, db.ForeignKey('retail_shop.id'), nullable=True) current_status_id = db.Column(db.Integer, db.ForeignKey('status.id'), nullable=True) items = db.relationship('Item', uselist=True, back_populates='order', lazy='dynamic') customer = db.relationship('Customer', foreign_keys=[customer_id]) retail_shop = db.relationship('RetailShop', foreign_keys=[retail_shop_id]) discounts = db.relationship('Discount', secondary='order_discount', uselist=True) denominations = db.relationship('Denomination', secondary='order_denomination', uselist=False) current_status = db.relationship('Status', uselist=False, foreign_keys=[current_status_id]) time_line = db.relationship('Status', secondary='order_status') @hybrid_property def total_discount(self): return sum([ discount.value if discount.type == 'VALUE' else float(self.total * discount / 100) for discount in self.discounts ]) @hybrid_property def items_count(self): return self.order_items.with_entities(func.Count(Item.id)).scalar() @items_count.expression def items_count(cls): return select([func.Count(Item.id) ]).where(Item.order_id == cls.id).as_scalar() @hybrid_property def amount_due(self): if self.total and self.amount_paid: return self.total - self.amount_paid return self.total
class TaskChoice(db.Model, BaseMixin): choice = db.Column(db.String(120), nullable=False) choice_group = db.relationship('ChoiceGroupToChoice', back_populates='choice')
class TaskStatus(db.Model, BaseMixin, ReprMixin): name = db.Column(db.String(128), nullable=False) code = db.Column(db.Integer, nullable=False)
class Anime(db.Model): """Lists AA details for anime""" __tablename__ = 'anime' __table_args__ = {"useexisting": True} malId = db.Column(db.Integer, primary_key=True) type = db.Column(db.Integer, default=1) status = db.Column(db.Integer, default=1) title = db.Column(db.String, default='') engTitle = db.Column(db.String, default='') japTitle = db.Column(db.String, default='') imgLink = db.Column(db.String, default='') startDate = db.Column(db.Date, default=DEFAULT_DATE) endDate = db.Column(db.Date, default=DEFAULT_DATE) episodes = db.Column(db.Integer, default=0) duration = db.Column(db.Integer, default=0) description = db.Column(db.String, default='') score = db.Column(db.Float, default=0) favorites = db.Column(db.Integer, default=0) members = db.Column(db.Integer, default=0) scoreCount = db.Column(db.Integer, default=0) genres = db.Column(db.String, default='') def get(self, field): """ Translate corresponding field to printable format :param field: Field to translate :return: Field in printable format """ return ANIME_RESULTS_FIELDS.get(field, lambda x: x)(getattr(self, field)) def __init__(self, mal_id): self.malId = mal_id def __repr__(self): '<Anime {}, Title {}>'.format(self.malId, self.title)
class PriorityArrayModel(db.Model): __tablename__ = 'priority_array' point_uuid = db.Column(db.String, db.ForeignKey('points.uuid'), primary_key=True, nullable=False) _1 = db.Column(db.Float(), nullable=True) _2 = db.Column(db.Float(), nullable=True) _3 = db.Column(db.Float(), nullable=True) _4 = db.Column(db.Float(), nullable=True) _5 = db.Column(db.Float(), nullable=True) _6 = db.Column(db.Float(), nullable=True) _7 = db.Column(db.Float(), nullable=True) _8 = db.Column(db.Float(), nullable=True) _9 = db.Column(db.Float(), nullable=True) _10 = db.Column(db.Float(), nullable=True) _11 = db.Column(db.Float(), nullable=True) _12 = db.Column(db.Float(), nullable=True) _13 = db.Column(db.Float(), nullable=True) _14 = db.Column(db.Float(), nullable=True) _15 = db.Column(db.Float(), nullable=True) _16 = db.Column(db.Float(), nullable=True) def __repr__(self): return f"PriorityArray(uuid = {self.point_uuid})" def to_dict(self) -> dict: return { c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs } def delete_from_db(self): db.session.delete(self) db.session.commit() def update_with_no_commit(self, **kwargs): for key, value in kwargs.items(): if hasattr(self, key): setattr(self, key, value) return self.check_self() def update(self, **kwargs): highest_priority_value: float = self.update_with_no_commit(**kwargs) db.session.commit() return highest_priority_value def check_self(self) -> float: highest_priority_value: float = self.get_highest_priority_value_from_priority_array( self) if highest_priority_value is None: from src.models.point.model_point import PointModel point: PointModel = self.point self._16 = point.fallback_value highest_priority_value = point.fallback_value return highest_priority_value @classmethod def create_priority_array_model(cls, point_uuid, priority_array_write, fallback_value): priority_array = PriorityArrayModel(point_uuid=point_uuid, **priority_array_write) if cls.get_highest_priority_value_from_priority_array( priority_array) is None: priority_array._16 = fallback_value return priority_array @classmethod def find_by_point_uuid(cls, point_uuid): return cls.query.filter_by(point_uuid=point_uuid).first() @classmethod def get_highest_priority_value(cls, point_uuid): priority_array: PriorityArrayModel = cls.find_by_point_uuid(point_uuid) return cls.get_highest_priority_value_from_priority_array( priority_array) @classmethod def get_highest_priority_value_from_priority_array(cls, priority_array): if priority_array: for i in range(1, 17): value = getattr(priority_array, f'_{i}', None) if value is not None: return value return None
class Book_tour_items(db.Model): __tablename__ = 'book_tour_items' id = db.Column(db.Integer, primary_key=True) book_tourItem_id = db.Column(db.Integer, db.ForeignKey('book_tours.id'), nullable=False) payment = db.Column(db.Integer, nullable=False) languages = db.Column(db.String(255), nullable=True) tour_name = db.Column(db.String(255), nullable=True) book_date = db.Column(db.Date, nullable=True) first_name = db.Column(db.String(255), nullable=True) last_name = db.Column(db.String(255), nullable=True) country = db.Column(db.Text, nullable=True) phone = db.Column(db.String(255), nullable=True) email = db.Column(db.String(255), nullable=False) # ExpInfo = db.relationship('Exp', backref="product_exp", useList=False) #one to one def render(self): return { "id": self.id, "tour_id": self.tour_id, "payment": self.payment, "languages": self.languages, "tour_name": self.tour_name, "book_date": self.book_date, "first_name": self.first_name, "last_name": self.last_name, "country": self.country, "phone": self.phone, "email": self.email }
class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255))
class Order(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) tickets = db.relationship('Ticket', backref='order', lazy=True) status = db.Column(db.String, nullable=False)
from src import db from src.utils.models import ResourceMixin grp_members = db.Table( 'group_members', db.Column('group_id', db.Integer, db.ForeignKey('groups.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True), db.Column('user_id', db.Integer, db.ForeignKey('users.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True)) grp_perms = db.Table( 'group_permissions', db.Column('group_id', db.Integer, db.ForeignKey('groups.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True), db.Column('perm_id', db.Integer, db.ForeignKey('permissions.id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True))
class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(50), unique=True) users = db.relationship('User', backref=db.backref('role'))
class User(UserMixin, db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) # User Authentication fields email = db.Column(db.String(255), nullable=False, unique=True) email_confirmed_at = db.Column(db.DateTime(timezone=True)) username = db.Column(db.String(50), nullable=False) password = db.Column(db.String(255), nullable=False) timestamp = db.Column(db.DateTime(timezone=True), server_default = db.func.now()) test = db.Column(db.String(50)) #relationship role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) events = db.relationship('Event', secondary='attends', backref=db.backref('users', lazy=True)) orders = db.relationship('Order', backref=db.backref('user', lazy=True)) # User fields avatar_url = db.Column(db.Text) active = db.Column(db.Boolean()) first_name = db.Column(db.String(50)) last_name = db.Column(db.String(50)) birthday = db.Column(db.DateTime(timezone=True)) def set_password(self, password): self.password = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password, password) def check_email(self, email): return User.query.filter_by(email = email).first() def cart(self): order = Order.query.filter_by(client_id = self.id, isPaid = False).first() if not order: order = Order(client_id=user.id) db.session.add(order) db.session.commit() return order
class Orderitem(db.Model): __tablename__ = 'orderitems' id = db.Column(db.Integer, primary_key=True) order_id = db.Column(db.Integer, db.ForeignKey('orders.id')) tickettype_id = db.Column(db.Integer, db.ForeignKey('tickettypes.id')) amount = db.Column(db.Integer, nullable=False, default=1)
class Category(db.Model): __tablename__ = 'categories' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(200), nullable=False, unique=True)
end_date = db.Column(db.DateTime(timezone=True), nullable=False, default=datetime) location = db.Column(db.Text, nullable = False) timestamp = db.Column(db.DateTime(timezone=True), server_default = db.func.now()) #event properties images = db.relationship('Image', backref='event') articles = db.relationship('Article', backref='event') tickettypes = db.relationship('Tickettype', backref='event') interested_people = db.relationship('User', secondary='interests', backref=db.backref('interested_events', lazy=True)) categories = db.relationship('Category', secondary='category_events', backref=db.backref('events', lazy=True)) def check_event(self, name): return Event.query.filter_by(name = name).first() attends = db.Table('attends', db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('event_id', db.Integer, db.ForeignKey('events.id')) ) class Image(db.Model): __tablename__ = 'images' id = db.Column(db.Integer, primary_key=True) image_name = db.Column(db.String(200)) image_url = db.Column(db.Text, nullable=False) event_id = db.Column(db.Integer, db.ForeignKey('events.id')) timestamp = db.Column(db.DateTime(timezone=True), server_default = db.func.now()) class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(200))
class TbCreditLog(db.Model): """ 征信日志,调用流水 """ __bind_key__ = "log_db" __tablename__ = 'tb_credit_log' id = db.Column(db.Integer, primary_key=True, comment="自增ID") seq_no = db.Column(db.String(50), nullable=False, comment="调用流水ID") index_key = db.Column(db.String(100), nullable=False, comment="查询索引") interface = db.Column(db.String(20), nullable=False, comment="接口编码") supplier = db.Column(db.String(100), nullable=False, comment="供应商") product = db.Column(db.String(100), nullable=False, comment="供应商产品名称") type = db.Column(db.String(20), nullable=False, comment="接口类型") merchant_code = db.Column(db.String(32), nullable=True, comment="租户ID") production_code = db.Column(db.String(32), nullable=True, comment="产品ID") uin = db.Column(db.BigInteger, nullable=False, comment="用户ID") name = db.Column(db.String(100), nullable=False, comment="用户姓名") id_type = db.Column(db.String(10), nullable=False, comment="证件类型") id_card = db.Column(db.String(50), nullable=False, comment="证件号码") phone = db.Column(db.String(30), nullable=False, comment="手机号码") url = db.Column(db.String(200), comment="请求地址") price = db.Column(db.Numeric, nullable=True, comment="调用价格") start_time = db.Column(db.BigInteger, nullable=False, comment="调用开始时间") end_time = db.Column(db.BigInteger, nullable=True, comment="调用结束时间") status = db.Column(db.String(10), nullable=True, comment="调用结果") update_time = db.Column(db.BigInteger, nullable=False, comment="更新时间") def to_json(self): return { 'id': self.id, 'merchant_code': self.merchant_code or "", 'production_code': self.production_code or "", 'seq_no': self.seq_no, 'interface': self.interface, 'supplier': self.supplier, 'product': self.product, 'type': self.type, 'uin': self.uin, 'name': self.name, 'id_type': self.id_type, 'id_card': self.id_card, 'phone': self.phone, 'url': self.url or '', 'start_time': self.start_time or '', 'status': self.status or '', 'price': str(self.price or 0), 'end_time': self.end_time or '', 'update_time': self.update_time or '' } def to_pretty(self): return { 'id': self.id, 'merchant_code': self.merchant_code or "", 'production_code': self.production_code or "", 'supplier': self.supplier, 'product': self.product, 'type': self.type, 'name': self.name, 'id_card': self.id_card, 'id_type': self.id_type, 'phone': self.phone, 'start_time': self.start_time or '', 'price': str(self.price or ''), 'update_time': self.update_time or '' }
from src import db event_category = db.Table( 'event_category', db.Column('event_id', db.Integer, db.ForeignKey('event.id'), primary_key=True), db.Column('category_id', db.Integer, db.ForeignKey('category.id'), primary_key=True)) class Events(db.Model): #Location __tablename__ = 'event' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(132), nullable=False) description = db.Column(db.Text, nullable=False) start_time = db.Column(db.DateTime) end_time = db.Column(db.DateTime) organizer_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) ticket_types = db.relationship('TicketTypes', backref='event', lazy=True) categories = db.relationship('Category', secondary=event_category,
class Ticket(db.Model): id = db.Column(db.Integer, primary_key=True) quantity = db.Column(db.Integer) title = db.Column(db.String) event_id = db.Column(db.Integer)
class Post(db.Model): post_num = db.Column(db.Integer, primary_key=True) date = db.Column(db.DateTime) email = db.Column(db.String(255)) subject = db.Column(db.String(255)) message = db.Column(db.Text) flag = db.Column(db.String(255)) flag_name = db.Column(db.String(255)) mod = db.Column(db.String(255), default=None) is_op = db.Column(db.Boolean, default=False) ban_message = db.Column(db.String(255), default=None) parent_thread = db.Column(db.Integer, db.ForeignKey('thread.thread_num'), nullable=False) files_contained = db.relationship('File', backref='post', cascade='delete', lazy='subquery') reports_submitted = db.relationship('Report', backref='post') markdown = db.Column(db.Text) tsv_message = db.Column(TSVECTOR) tsv_subject = db.Column(TSVECTOR) @property def formatted_message(self): return format_message(self.message) @property def timedelta(self): td = datetime.utcnow() - self.date return f'Posted {format_timedelta(td)} ago' def get_replies(self, posts): replies = [] for post in posts: if f'>>{self.post_num}' in post.message: replies.append(post.post_num) return replies
from hashlib import md5 from src.utils.serializer_helper import serialize_data from datetime import datetime from sqlalchemy.ext.hybrid import hybrid_property from flask_security import RoleMixin, UserMixin from src import db, BaseMixin, ReprMixin roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, BaseMixin, UserMixin, ReprMixin): email = db.Column(db.String(127), unique=True, nullable=False) password = db.Column(db.String(255), default='', nullable=False) username = db.Column(db.String(127), nullable=True) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) last_login_at = db.Column(db.DateTime()) current_login_at = db.Column(db.DateTime()) last_login_ip = db.Column(db.String(45)) current_login_ip = db.Column(db.String(45)) login_count = db.Column(db.Integer)
class Phone(db.Model): __tablename__ = 'hashes' hash = db.Column(db.String(64), primary_key=True) phone = db.Column(db.String(15))
class PointModel(ModelBase): __tablename__ = 'points' uuid = db.Column(db.String(80), primary_key=True, nullable=False) name = db.Column(db.String(80), nullable=False) device_uuid = db.Column(db.String, db.ForeignKey('devices.uuid'), nullable=False) enable = db.Column(db.Boolean(), nullable=False, default=True) history_enable = db.Column(db.Boolean(), nullable=False, default=True) history_type = db.Column(db.Enum(HistoryType), nullable=False, default=HistoryType.INTERVAL) history_interval = db.Column(db.Integer, nullable=False, default=15) writable = db.Column(db.Boolean, nullable=False, default=True) priority_array_write = db.relationship('PriorityArrayModel', backref='point', lazy=True, uselist=False, cascade="all,delete") cov_threshold = db.Column(db.Float, nullable=False, default=0) value_round = db.Column(db.Integer(), nullable=False, default=2) value_operation = db.Column(db.String, nullable=True, default="x + 0") input_min = db.Column(db.Float()) input_max = db.Column(db.Float()) scale_min = db.Column(db.Float()) scale_max = db.Column(db.Float()) tags = db.Column(db.String(320), nullable=True) point_store = db.relationship('PointStoreModel', backref='point', lazy=True, uselist=False, cascade="all,delete") point_store_history = db.relationship('PointStoreHistoryModel', backref='point', lazy=True, cascade="all,delete") history_sync_log = db.relationship('HistorySyncLogModel', backref='hsl', lazy=True, cascade="all,delete") fallback_value = db.Column(db.Float(), nullable=True) disable_mqtt = db.Column(db.Boolean, nullable=False, default=True) type = db.Column(db.Enum(GenericPointType), nullable=False, default=GenericPointType.FLOAT) unit = db.Column(db.String, nullable=True) __table_args__ = (UniqueConstraint('name', 'device_uuid'), ) def __repr__(self): return f"Point(uuid = {self.uuid})" @validates('name') def validate_name(self, _, value): if not re.match("^([A-Za-z0-9_-])+$", value): raise ValueError( "name should be alphanumeric and can contain '_', '-'") return value @validates('value_operation') def validate_value_operation(self, _, value): try: if value and value.strip(): eval_arithmetic_expression(value.lower().replace( 'x', str(random.randint(1, 9)))) except Exception: raise ValueError( "Invalid value_operation, must be a valid arithmetic expression" ) return value @classmethod def find_by_name(cls, network_name: str, device_name: str, point_name: str): results = cls.query.filter_by(name=point_name) \ .join(DeviceModel).filter_by(name=device_name) \ .join(NetworkModel).filter_by(name=network_name) \ .first() return results def save_to_db(self): self.point_store = PointStoreModel.create_new_point_store_model( self.uuid) super().save_to_db() def update_point_value( self, point_store: PointStoreModel, cov_threshold: float = None, priority_array_write_obj: PriorityArrayModel = None) -> bool: if not point_store.fault: if cov_threshold is None: cov_threshold = self.cov_threshold value = point_store.value_original if value is not None: value = self.apply_scale(value, self.input_min, self.input_max, self.scale_min, self.scale_max) value = self.apply_value_operation(value, self.value_operation) value = round(value, self.value_round) point_store.value = self.apply_point_type(value) return point_store.update(cov_threshold, priority_array_write_obj) @validates('tags') def validate_tags(self, _, value): """ Rules for tags: - force all tags to be lower case - if there is a gap add an underscore - no special characters """ if value is not None: try: return validate_json(value) except ValueError: raise ValueError('tags needs to be a valid JSON') return value @validates('history_interval') def validate_history_interval(self, _, value): if self.history_type == HistoryType.INTERVAL and value is not None and value < 1: raise ValueError( "history_interval needs to be at least 1, default is 15 (in minutes)" ) return value @validates('input_min') def validate_input_min(self, _, value): if value is not None and self.input_max is not None and value > self.input_max: raise ValueError("input_min cannot be greater than input_max") return value @validates('input_max') def validate_input_max(self, _, value): if self.input_min is not None and value is not None and self.input_min > value: raise ValueError("input_min cannot be greater than input_max") return value @validates('scale_min') def validate_scale_min(self, _, value): if value is not None and self.scale_max is not None and value > self.scale_max: raise ValueError("scale_min cannot be greater than scale_max") return value @validates('scale_max') def validate_scale_max(self, _, value): if self.scale_min is not None and value is not None and self.scale_min > value: raise ValueError("scale_min cannot be greater than scale_max") return value def update(self, **kwargs) -> bool: publish_cov: bool = self.disable_mqtt != kwargs.get('disable_mqtt') changed: bool = super().update(**kwargs) updated: bool = self.update_point_value(self.point_store, 0) if updated or publish_cov: self.publish_cov(self.point_store) return changed def update_point_store(self, value: float, priority: int, priority_array_write: dict): priority_array_write_obj, highest_priority_value = self.update_priority_value_without_commit( value, priority, priority_array_write) point_store = PointStoreModel(point_uuid=self.uuid, value_original=highest_priority_value) updated = self.update_point_value( point_store, priority_array_write_obj=priority_array_write_obj) if updated: self.publish_cov(point_store) def update_priority_value_without_commit(self, value: float, priority: int, priority_array_write: dict) -> \ (Union[PriorityArrayModel, None], Union[float, None]): if priority_array_write: priority_array: PriorityArrayModel = PriorityArrayModel.find_by_point_uuid( self.uuid) if priority_array: highest_priority_value: float = priority_array.update_with_no_commit( **priority_array_write) return priority_array, highest_priority_value return None, None if not priority: priority = 16 if priority not in range(1, 17): raise ValueError('priority should be in range(1, 17)') if priority: priority_array: PriorityArrayModel = PriorityArrayModel.find_by_point_uuid( self.uuid) if priority_array: highest_priority_value: float = priority_array.update_with_no_commit( **{f"_{priority}": value}) return priority_array, highest_priority_value return None, None def update_priority_value(self, value: float, priority: int, priority_array_write: dict): self.update_priority_value_without_commit(value, priority, priority_array_write) db.session.commit() @classmethod def apply_value_operation(cls, original_value, value_operation: str) -> float or None: """Do calculations on original value with the help of point details""" if original_value is None or value_operation is None or not value_operation.strip( ): return original_value return eval_arithmetic_expression(value_operation.lower().replace( 'x', str(original_value))) @classmethod def apply_scale(cls, value: float, input_min: float, input_max: float, output_min: float, output_max: float) \ -> float or None: if value is None or input_min is None or input_max is None or output_min is None or output_max is None: return value if input_min == input_max or output_min == output_max: return value scaled = ( (value - input_min) / (input_max - input_min)) * (output_max - output_min) + output_min if scaled > max(output_max, output_min): return max(output_max, output_min) elif scaled < min(output_max, output_min): return min(output_max, output_min) else: return scaled def apply_point_type(self, value: float): if value is not None: if self.type == GenericPointType.STRING: value = None elif self.type == GenericPointType.INT: value = round(value, 0) elif self.type == GenericPointType.BOOL: value = float(bool(value)) return value def publish_cov(self, point_store: PointStoreModel, device: DeviceModel = None, network: NetworkModel = None, force_clear: bool = False): if point_store is None: raise Exception('Point.publish_cov point_store cannot be None') if device is None: device = DeviceModel.find_by_uuid(self.device_uuid) if network is None: network = NetworkModel.find_by_uuid(device.network_uuid) if device is None or network is None: raise Exception( f'Cannot find network or device for point {self.uuid}') priority = self._get_highest_priority_field() if self.history_enable \ and (self.history_type == HistoryType.COV or self.history_type == HistoryType.COV_AND_INTERVAL) \ and network.history_enable \ and device.history_enable: PointStoreHistoryModel.create_history(point_store) db.session.commit() if not self.disable_mqtt: from src.services.mqtt_client import MqttClient MqttClient.publish_point_cov(Drivers.GENERIC.name, network, device, self, point_store, force_clear, priority) def _get_highest_priority_field(self): for i in range(1, 17): value = getattr(self.priority_array_write, f'_{i}', None) if value is not None: return i return 16
class Token(db.Model): id = db.Column(db.Integer, primary_key=True) uuid = db.Column(db.String, unique=True) user_id = db.Column(db.Integer, db.ForeignKey(Member.id), nullable=False) user = db.relationship(Member)
class UserToAnime(db.Model): """Maps user to anime they have categorized""" __tablename__ = 'user_to_anime' __table_args__ = {"useexisting": True} userId = db.Column(db.Integer, primary_key=True) malId = db.Column(db.Integer, primary_key=True) myId = db.Column(db.Integer, default=0) myEpisodes = db.Column(db.Integer, default=0) myStartDate = db.Column(db.Date, default=DEFAULT_DATE) myEndDate = db.Column(db.Date, default=DEFAULT_DATE) myScore = db.Column(db.Integer, default=0) myStatus = db.Column(db.Integer, default=1) myRewatching = db.Column(db.Boolean, default=False) myRewatchEps = db.Column(db.Integer, default=0) myLastUpdate = db.Column(db.DateTime, default=DEFAULT_DATE) def __init__(self, user_id, anime_id): self.userId = user_id self.malId = anime_id def __repr__(self): '<User {}, Anime {}>'.format(self.userId, self.malId) def getFields(self, fields): ret = {} for field in fields: ret[field] = getattr(self, field) return ret def __eq__(self, other): return self.userId == other.userId and self.malId == other.malId
class OAuth(OAuthConsumerMixin, db.Model): provider_user_id = db.Column(db.String(256), unique=True, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey(Member.id), nullable=False) user = db.relationship(Member)
class Task(db.Model, SerializerMixin): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(128)) content = db.Column(db.String(512)) date = db.Column(db.Date, nullable=False)
import uuid from werkzeug.security import generate_password_hash from src import db films_actors = db.Table( 'films_actors', db.Column('actor_id', db.Integer, db.ForeignKey('actors.id'), primary_key=True), db.Column('film_id', db.Integer, db.ForeignKey('films.id'), primary_key=True)) class Film(db.Model): __tablename__ = 'films' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(120), nullable=False) release_date = db.Column(db.Date, nullable=False, index=True) uuid = db.Column(db.String(36), unique=True) description = db.Column(db.Text) distributed_by = db.Column(db.String(120), nullable=False) length = db.Column(db.Float) rating = db.Column(db.Float) age_rating = db.Column(db.Integer) actors = db.relationship('Actor',
class QuestionType(db.Model, BaseMixin, ReprMixin): name = db.Column(db.String(80), nullable=False) parent_id = db.Column(db.Integer, db.ForeignKey('question_type.id'), nullable=True)
class User(db.Model): """ This class defines the users table """ __tablename__ = "user" # internal_id = db.Column(db.Integer, primary_key=True) # sub from id.token claims from azure - used to identify user, and passed to client id = db.Column(db.Text, primary_key=True, unique=True) email = db.Column(db.String(256), unique=True) created_at = db.Column(db.DateTime, nullable=False) # 1 is admin, 2 is super admin role = db.Column(db.Integer, nullable=True) qualities = db.relationship("Quality", backref="user", lazy=True) difficulties = db.relationship("Difficulty", backref="user", lazy=True) time_spent = db.relationship("TimeSpent", backref="user", lazy=True) def __str__(self): votes = {} relationships = [ { "label": "quality", "rel": self.qualities }, { "label": "difficulty", "rel": self.difficulties }, { "label": "time", "rel": self.time_spent }, ] for r in relationships: for x in r.get("rel"): if votes.get(x.cid): votes[x.cid] = {**votes[x.cid], r.get("label"): x.rating} else: votes[x.cid] = {r.get("label"): x.rating} return { "id": self.id, "email": self.email, "role": self.role, "votes": votes } def __init__(self, id: str, email: str): """ """ self.id = id self.email = email self.created_at = datetime.now() self.role = 0 def save(self): """ Save user to DB (creation and updating). :return: """ db.session.add(self) db.session.commit() def delete(self): """ Delete user from DB. :return: """ relationships = [self.qualities, self.difficulties, self.time_spent] for rel in relationships: for i in rel: i.delete() db.session.delete(self) db.session.commit() @staticmethod def save_user_session_id(id): """ Sets the 'current_user' session id :param id: string :return: """ try: session["current_user"] = id session.permanent = True except Exception as e: return e @staticmethod def get_user_session_id(): """ Gets session user id :return: id, string """ try: return session["current_user"] except Exception as e: return e @staticmethod def clear_user_session_id(): """ Removes user id from session :return: """ session.pop("current_user", None)
class ChoiceGroup(db.Model, BaseMixin, ReprMixin): name = db.Column(db.String(80), nullable=False) choices = db.relationship('ChoiceGroupToChoice', back_populates='choice_group')
class Denomination(db.Model, BaseMixin, ReprMixin): value = db.Column(db.SmallInteger, default=0) name = db.Column(db.String, nullable=False, default='zero')