class Team(BaseModel): user = ForeignKeyField(User, related_name="team") name = CharField(verbose_name="团队名称", max_length=150, null=False, default="") team_type = CharField(verbose_name="团队类型", max_length=10, null=False, default="", choices=TEAM_TYPE) status = CharField(verbose_name="团队状态", max_length=10, null=False, default="") location = ForeignKeyField(Address) logo = CharField(verbose_name="公司logo", max_length=200, null=False, default="") link = CharField(verbose_name="官网地址", max_length=100, null=False, default="") is_verify = BooleanField(verbose_name="是否认证", null=False, default=False) create_at = DateTimeField(verbose_name="创建时间", null=False, default=utils.now) update_at = DateTimeField(verbose_name="创建时间", null=False, default=utils.now) uuid = CharField(verbose_name="uuid", max_length=32, null=False, default=utils.generate_id, unique=True) trust_amount = DecimalField(verbose_name="托管金额", max_digits=8, decimal_places=2, default=0) expend_amount = DecimalField(verbose_name="累计支付", max_digits=8, decimal_places=2, default=0)
class Session(BaseModel): s_id = CharField(max_length=20, unique=True) date_created = DateTimeField() upload_folder = CharField(max_length=20) last_ping = DateTimeField() status = CharField(default="reset") keep_active = BooleanField(default=False) # Uploads made by the server must be keep active @classmethod def new(cls, keep_active=False): from dgenies.lib.functions import Functions my_s_id = Functions.random_string(20) while len(cls.select().where(cls.s_id == my_s_id)) > 0: my_s_id = Functions.random_string(20) upload_folder = Functions.random_string(20) tmp_dir = config.upload_folder upload_folder_path = os.path.join(tmp_dir, upload_folder) while os.path.exists(upload_folder_path): upload_folder = Functions.random_string(20) upload_folder_path = os.path.join(tmp_dir, upload_folder) cls.create(s_id=my_s_id, date_created=datetime.now(), upload_folder=upload_folder, last_ping=datetime.now(), keep_active=keep_active) return my_s_id def ask_for_upload(self, change_status=False): all_asked = Session.select().where((Session.status == "pending") | (Session.status == "active")).\ order_by(Session.date_created) nb_asked = len(all_asked) if self.status != "reset": change_status = False status = "pending" if self.status == "active" or (change_status and nb_asked < 5): status = "active" self.status = status self.last_ping = datetime.now() self.save() return self.status == "active" def ping(self): self.last_ping = datetime.now() self.save()
class Channel(ModelBase): channel_id = BigIntegerField(primary_key=True) guild_id = BigIntegerField(null=True) name = CharField(null=True, index=True) topic = TextField(null=True) type_ = SmallIntegerField(null=True) # First message sent in the channel first_message_id = BigIntegerField(null=True) deleted = BooleanField(default=False) class Meta: table_name = 'channels' @classmethod def generate_first_message_id(cls, channel_id): try: return Message.select(Message.id).where( (Message.channel_id == channel_id)).order_by( Message.id.asc()).limit(1).get().id except Message.DoesNotExist: return None @classmethod def from_disco_channel(cls, channel): # Upsert channel information channel = list( cls.insert( channel_id=channel.id, guild_id=channel.guild.id if channel.guild else None, name=channel.name or None, topic=channel.topic or None, type_=channel.type, ).on_conflict(conflict_target=cls.channel_id, preserve=(cls.channel_id, cls.guild_id, cls.type_), update={ cls.name: channel.name, cls.topic: channel.topic }).returning(cls.first_message_id).execute())[0] # Update the first message ID if not channel.first_message_id: cls.update(first_message_id=cls.generate_first_message_id( channel.id)).where(cls.channel_id == channel.id).execute()
class Server_Stats(BaseModel): server_id = IntegerField() time = DateTimeField(default=datetime.datetime.now) server_start_time = CharField() cpu_usage = FloatField() memory_usage = FloatField() max_players = IntegerField() online_players = IntegerField() players = CharField() motd = CharField() server_running = BooleanField() server_version = CharField() world_name = CharField() world_size = FloatField() server_ip = CharField() server_port = IntegerField() class Meta: table_name = "stats"
class NonSimulatedImageClick(Model): """Represent a click on an image.""" pk = AutoField(primary_key=True) click_set_id = CharField() user_id = IntegerField() logged_in = BooleanField() zooniverse_id = CharField() timestamp = DateTimeField() click_x = DecimalField(max_digits=15) click_y = DecimalField(max_digits=15) number_of_tracks = CharField() # 2, 3, 4, 5-10 or 10+ or weird projection = CharField() class Meta: """Provides peewee config.""" database = db table_name = "TBL_NON_SIMULATED_IMAGE_CLICK"
class PlPlugmapM(OperationsDBModel): checked_in = BooleanField(null=True) dirname = TextField(null=True) file = TextField(null=True) filename = TextField(null=True) fscan = IntegerField(column_name='fscan_id', null=True) fscan_mjd = IntegerField(null=True) md5_checksum = TextField(null=True) pk = PrimaryKeyField() plugging = ForeignKeyField(column_name='plugging_pk', null=True, model=Plugging, backref='plplugmapms', field='pk') pointing_name = CharField(null=True) class Meta: db_table = 'pl_plugmap_m' schema = 'platedb'
class Customer(BaseModel): """ This class defines Customer, which maintains the details of a customer at HP Norton """ logger.info('Note how we defined the class') logger.info( 'Specify the fields in our model, their lengths and if mandatory') logger.info( 'The customer ID must be a unique identifier for each customer') id = CharField(primary_key=True, max_length=5) firstname = CharField(max_length=30) lastname = CharField(max_length=30) address = CharField(max_length=30) phone = CharField(max_length=12) # Format is XXX-XXX-XXXX email = CharField(max_length=30) status = BooleanField() credit_limit = DecimalField(max_digits=7, decimal_places=2)
class ManualCandidate(BaseModel): name = CharField(index=True) constituency = CharField() party = CharField() currentLegislator = BooleanField() beenLegislator = CharField() dayOfBirth = CharField(null=True) age = CharField(null=True) photo = TextField(null=True) wiki = CharField(null=True) fbPage = TextField(null=True) fbPersonalPage = TextField(null=True) education = CharField(null=True) educationConn = TextField(null=True) experience = TextField(null=True) experienceConn = TextField(null=True) politics = TextField(null=True) politicsConn = TextField(null=True) other = TextField(null=True)
class Gym(BaseModel): UNCONTESTED = 0 TEAM_MYSTIC = 1 TEAM_VALOR = 2 TEAM_INSTINCT = 3 gym_id = Utf8mb4CharField(primary_key=True, max_length=50) team_id = SmallIntegerField() guard_pokemon_id = SmallIntegerField() slots_available = SmallIntegerField() enabled = BooleanField() latitude = DoubleField() longitude = DoubleField() total_cp = SmallIntegerField() last_modified = DateTimeField(index=True) last_scanned = DateTimeField(default=datetime.utcnow, index=True) class Meta: indexes = ((('latitude', 'longitude'), False), )
class LegacyDeviceKeys(Model): curve_key = TextField() deleted = BooleanField() device = ForeignKeyField( column_name="device_id", field="device_id", model=LegacyAccounts, on_delete="CASCADE" ) ed_key = TextField() user_device_id = TextField() user_id = TextField() class Meta: table_name = "device_keys" indexes = ( (("device", "user_id", "user_device_id"), True), ) primary_key = CompositeKey("device", "user_device_id", "user_id")
class Customer(BaseModel): """ This class defines Customer, which maintains details of customers for whom we want to research career to date. """ logger.info('Note how we defined the class') logger.info('Specify the fields in our model, their lengths and if \ mandatory') logger.info('Must be a unique identifier for each customer') customer_id = CharField(primary_key=True, max_length=30) first_name = CharField(max_length=30) last_name = CharField(max_length=30) home_address = CharField(max_length=50) phone_number = CharField(max_length=20) email_address = CharField(max_length=20) status = BooleanField() credit_limit = FloatField()
class User(Model): """ User instance will creating from telegram api result message. user_id, username, first_name, last_name - this fields getting from telegram api message from user. is_sudo. Superuser can send sudo commands to chat. """ telegram_id = IntegerField(unique=True, verbose_name='Telegram id пользователя') username = CharField(null=True, verbose_name='Никнейм') first_name = CharField(null=True, verbose_name='Имя пользователя') last_name = CharField(null=True, verbose_name='Фамилия') is_sudo = BooleanField(default=False, verbose_name='Суперпользователь') class Meta: database = db def __repr__(self): return f'{self.user_id} {self.username} {self.first_name} {self.last_name} {self.is_sudo} ' \ f'{self.is_banned} {self.warn}'
class User(BaseModel): pin = CharField(primary_key=True) active = BooleanField(default=False) def __repr__(self): return '<USER> PIN:{}'.format(self.pin) @db.atomic() def set_active(self, status): self.active = status self.save() @staticmethod @db.atomic() def create_user(pin): user, was_created = User.create_or_get(pin=pin) if was_created: user.save() return user
class Image(BaseModel): volume = ForeignKeyField(Volume, on_delete='cascade', related_name='images') page = IntegerField() filename = CharField() mimetype = CharField() thumb_ok = BooleanField(default=False) # Set True if thumbnail successfully generated created_at = DateTimeField(default=datetime.now()) updated_at = DateTimeField(null=True) deleted_at = DateTimeField(null=True) class Meta: order_by = ('page',) def __unicode__(self): return self.filename + ' ' + self.page def __str__(self): return self.filename + ' ' + self.page
class Customer(BaseModel): """ This class defines Customer, which maintains the details of the customer's contact information. """ customer_id = AutoField() # Auto-incrementing primary key. customer_name = CharField(max_length=50) customer_lastname = CharField(max_length=50) customer_address = CharField(max_length=300, null=True) customer_phone_number = CharField(max_length=20, null=True) customer_email = CharField(max_length=100, null=True) status = BooleanField(default=False) credit_limit = DoubleField(null=True) # credit_limit = DecimalField(max_digits=18, decimal_places=2) class Meta: """ Meta class to name the table """ table_name = 'customers'
class User(BaseModel): id = PrimaryKeyField() uuid = UUIDField(constraints=[SQL('DEFAULT uuid_generate_v4()')], unique=True) fname = CharField() sname = CharField() email = CharField(unique=True) profile_image_url = CharField(null=True) password = CharField() activated = BooleanField(default=False) activation_key = CharField(default=secrets.token_urlsafe()) registered_on = DateTimeField(default=datetime.datetime.now) # TODO: return User type @staticmethod def from_object(user: Dict): """ returns a User object from a dictionary (used for session user) """ return dict_to_model(data=user, model_class=User)
class Tables(BaseModel): restaurant = ForeignKeyField(Restaurant) size = IntegerField() shape = IntegerField() occupied = BooleanField() posX = FloatField() posY = FloatField() @classmethod def create_tables(cls,restaurant,size, occupied, posX, posY, shape): '''Creates a new reservation Args: id(int): A unique identifier for the table restaurant(int): The foreign key of the restaurant size(int): The max number of guests a table can seat occupied(bool): Determines if a table is occupied. 0 is not occupied, and 1 is occupied posX(float): The relative x position of the table posY(float): The relative y position of the table shape(int): An integer representing the shape of the table. 0 = Circle, 1 = Square, 2 = Rectangle, 3 = Vertical Rectangle Returns: N/A Raises: ValueError: ''' try: tb = cls.create( restaurant=restaurant, size=size, occupied=occupied, posX=posX,posY=posY, shape=shape) return [tb.posX,tb.posY,tb.occupied,tb.id] except IntegrityError: raise ValueError("This should not happen(Table)") @classmethod def delTable(cls,id): try: res = cls.get(cls.id == id) res.delete_instance() return except IntegrityError: raise ValueError("This should not happen(Table)")
class Users(Base): """ Users. """ id = PrimaryKeyField(primary_key=True) name = CharField(unique=True) email = CharField() password = CharField() rank = IntegerField() enabled = BooleanField() last_login = DateTimeField(null=True) def can(self, requested_action, item): if self.rank == 10: return True else: if requested_action == 'create': action = 'read' else: action = requested_action model_name = getattr(item._meta, 'db_table') rules = AccessRules.select()\ .where((AccessRules.user == self.id) | (AccessRules.rank == self.rank))\ .where(AccessRules.model == model_name)\ .where((AccessRules.item == None) | (AccessRules.item == item.id))\ .where(getattr(AccessRules, action) != None)\ .order_by(AccessRules.level.desc(), AccessRules.item.asc(), AccessRules.rank.desc())\ .limit(1) if len(rules) > 0: if requested_action == 'create': if getattr(rules[0], action) >= 5: return True else: return False else: if getattr(rules[0], action) >= 1: return True else: return False return False
class User(Model): username = CharField(max_length=150, unique=True) password = CharField(max_length=150) is_active = BooleanField(default=True) tags = ArrayField(field_class=CharField) name = CharField(max_length=150) email = CharField(max_length=200, index=True) class Meta: table_name = 'users' database = db @staticmethod def set_password(raw_password: str) -> str: return create_password(raw_password=raw_password) def check_password(self, raw_password: str) -> bool: return verify_password(raw_password=raw_password, hash_pass=str(self.password))
class User(UserMixin, BaseModel): username = CharField() password = CharField() fullname = CharField() email = CharField(null=True) phone = CharField() address = CharField(null=True) role = CharField() status = BooleanField(default=True) created_at = DateTimeField() created_by = IntegerField() updated_at = DateTimeField(null=True) updated_by = IntegerField(null=True) def verify_password(self, raw_password): return check_password_hash(self.password, raw_password) def generate_password(self, password): return generate_password_hash(password)
class ImageModel(Model): """Model for images.""" class Meta: """TODO document this.""" database = db table_name = IMAGES_TABLE id = UUIDField(unique=True, null=False, primary_key=True) user_id = ForeignKeyField( UserModel, on_delete="CASCADE", on_update="CASCADE", column_name="user_id", ) format = CharField(null=True) is_profile = BooleanField(default=False) create_time = TimestampField(default=None, resolution=0, utc=False)
class User(Model, UserMixin): id = PrimaryKeyField() username = TextField(unique=True) email = TextField(unique=True) # Only enable email verification is mail is enabled if app.config["ENABLE_MAIL"] == True: verified_email = BooleanField() password = TextField() session_token = TextField(unique=True) vlads = IntegerField() client_seed = TextField(null=True) class Meta: database = db def get_id(self): return self.session_token
def main(): """ If you want to add other fileds import from peewee Fields: DateTimeField CharField PrimaryKeyField IntegerField ForeignKeyField BooleanField Ex. from pewee import ForeignKeyField """ try: logging.info("Add 'status' column on 'Host' table") recreating_field = BooleanField(default=False) migrate(migrator.add_column('host', 'recreating', recreating_field)) except Exception as e: logging.error(e)
class Polygon(ShapeType): abstract = False vertices = TextField() line_width = IntegerField() open_polygon = BooleanField() @staticmethod def pre_create(**kwargs): kwargs["vertices"] = json.dumps(kwargs["vertices"]) return kwargs def as_dict(self, *args, **kwargs): model = model_to_dict(self, *args, **kwargs) model["vertices"] = json.loads(model["vertices"]) return model def update_from_dict(self, data, *args, **kwargs): data["vertices"] = json.dumps(data["vertices"]) return update_model_from_dict(self, data, *args, **kwargs)
class SubPost(BaseModel): content = TextField(null=True) deleted = IntegerField( null=True) # 1=self delete, 2=mod delete, 0=not deleted distinguish = IntegerField(null=True) # 1=mod, 2=admin, 0 or null = normal link = CharField(null=True) nsfw = BooleanField(null=True) pid = PrimaryKeyField() posted = DateTimeField(null=True) edited = DateTimeField(null=True) ptype = IntegerField(null=True) # 1=text, 2=link, 3=poll score = IntegerField(null=True) # XXX: Deprecated upvotes = IntegerField(default=0) downvotes = IntegerField(default=0) sid = ForeignKeyField(db_column="sid", null=True, model=Sub, field="sid") thumbnail = CharField(null=True) title = CharField(null=True) comments = IntegerField() uid = ForeignKeyField(db_column="uid", null=True, model=User, field="uid", backref="posts") flair = CharField(null=True, max_length=25) def __repr__(self): return f'<SubPost "{self.title[:20]}">' def is_archived(self): delta = datetime.timedelta(days=config.site.archive_post_after) return (datetime.datetime.utcnow() - self.posted.replace(tzinfo=None)) > delta # noqa def is_title_editable(self): delta = datetime.timedelta(seconds=config.site.title_edit_timeout) return (datetime.datetime.utcnow() - self.posted.replace(tzinfo=None)) > delta # noqa class Meta: table_name = "sub_post"
class Article(Model): """ 文章表 分类和文章的关系在这里设置为一对多关系(为了与文章和标签关系形成区分) 也就是一篇博客只能在一个分类下面 用户和文章是一对多的关系 标签与文章是多对多的关系(用中介模型创建第三张表) # backref是反查的字段,如果有related_name用related_name反查,如果没有直接用petties反查 关于联表删除 """ id = AutoField(primary_key=True) title = CharField(max_length=50, verbose_name='文章标题') desc = CharField(max_length=255, verbose_name='文章描述') # 摘要 content = TextField(verbose_name='文章内容') category_id = ForeignKeyField(Category, null=True, backref='category') user_id = ForeignKeyField(User, null=True, backref='user') create_time = DateTimeField(default=datetime.datetime.now, verbose_name='创建时间') # 发布时间 update_time = DateTimeField(null=False, default=datetime.datetime.now, verbose_name='修改时间') is_delete = BooleanField(default=False, verbose_name="是否删除") def save(self, *args, **kwargs): self.update_time = datetime.datetime.now() return super(Article, self).save(*args, **kwargs) def to_dict(self): data = { "id": self.id, "title": self.title, "desc": self.desc, "content": self.content, "category_id": self.category_id, "user_id": self.user_id, "create_time": str(self.create_time), "update_time": str(self.update_time) } return data class Meta: database = database table_name = 'article'
class PrinterCommand(BaseModel): sequence = IntegerField(default=1) command = CharField() status = CharField(default="pending") nowait = BooleanField(default=False) response = JSONField(default=list) printer = ForeignKeyField(Printer, on_delete="CASCADE", related_name="commands", null=True, default=None, backref='commands') print = ForeignKeyField(Print, on_delete="CASCADE", related_name='commands', backref='commands', null=True, default=None) parent_id = IntegerField(default=0) parent_type = CharField(null=True) def identifier(self): cmd = self.command.strip("\n") return f'{cmd}:{self.created_at}' @property def serialize(self): return { 'id': self.id, 'command': self.command, 'status': self.status, 'response': self.response } def __repr__(self): return "{}, {}, {}".format(self.id, self.command, self.status) class Meta: table_name = "printer_commands"
class Tag(BaseModel): uid = CharField( unique=True, index=True, primary_key=True, ) # Unique tag/card/nfc id user = TextField(null=True) # user text tag_type = CharField(null=True) # album_local, album_spotify etc... data = CharField(null=True) # media uri or option description = TextField(null=True) # description text read_count = IntegerField(default=0) # Increment each time a tag is used last_read_date = TimestampField(null=True, utc=True) # timestamp of last used date option_type = CharField( default='normal' ) # option card type : normal (default), new (discover card:only play new tracks), favorites (preferred tracks), hidden (not considered by stats) option_new = BooleanField( null=True) # only play new tracks (depreciated, to be suppressed) option_sort = CharField( null=True) # shuffle, (asc, desc : date of tracks/podcasts) option_duration = IntegerField( null=True) # max duration of a media : mostly useful for radios option_max_results = IntegerField( null=True) # Max results associated to tag option_discover_level = IntegerField( default=5) # Discover level (0-10) associated to tag option_last_unread = IntegerField( null=True) # Podcasts max count to read in podcast channel def __str__(self): return "TAG UID : {} | TYPE : {} | MEDIA : {} | DESCRIPTION : {} | READ COUNT : {}| OPTION_TYPE : {}".format( self.uid, self.tag_type, self.data, self.description, self.read_count, self.option_type) def add_count(self): if self.read_count != None: self.read_count += 1 else: self.read_count = 1 self.last_read_date = datetime.datetime.utcnow() self.update() self.save()
class Block(BaseModel): height = IntegerField(index=True) hash = CharField(max_length=64, unique=True, index=True) timestamp = DateTimeField(index=True) merkle_root = CharField(max_length=64, unique=True) tx = BinaryJSONField() difficulty = FloatField() size = IntegerField() version = BlobField() bits = BlobField() nonce = BigIntegerField() chainwork = BlobField() coinbase = BlobField() tx_count = IntegerField() orphaned = BooleanField(default=False, index=True) def hash_rate(self): bnTarget = uint256_from_compact(bytes_to_int(self.bits)) diff = int('FFFF0000000000000000000000000000000000000000000000000000', 16) / bnTarget return int(diff * (2**32 / 60)) def to_json(self): pool = None cb = bytes(self.coinbase) for key, value in POOLS.items(): if cb.find(key.encode()) != -1: pool = value return { 'height': self.height, 'hash': self.hash, 'timestamp': int(self.timestamp.timestamp()), 'merkle_root': self.merkle_root, 'tx': self.tx, 'difficulty': self.difficulty, 'size': self.size, 'version_hex': bytes(self.version).hex(), 'version': struct.unpack('i', bytes(self.version))[0], 'bits': bytes(self.bits).hex(), 'nonce': self.nonce, 'pool': pool }
class Comment(BaseModel): commenter = ForeignKeyField(User, backref='comments') timestamp = DateTimeField(default=datetime.now) line_number = IntegerField(constraints=[Check('line_number >= 1')]) comment = ForeignKeyField(CommentText) solution = ForeignKeyField(Solution) is_auto = BooleanField(default=False) @classmethod def create_comment( cls, commenter: User, line_number: int, comment_text: CommentText, solution: Solution, is_auto: bool, ) -> 'Comment': return cls.get_or_create( commenter=commenter, line_number=line_number, comment=comment_text, solution=solution, is_auto=is_auto, ) @classmethod def by_solution(cls, solution_id: int): fields = [ cls.id, cls.line_number, cls.is_auto, CommentText.id.alias('comment_id'), CommentText.text, User.fullname.alias('author_name'), ] return (cls.select( *fields).join(CommentText).switch().join(User).where( cls.solution == solution_id)) @classmethod def get_solutions(cls, solution_id: int) -> Tuple[Dict[Any, Any], ...]: return tuple(cls.by_solution(solution_id).dicts())