class Comment(BaseModel): # 评论ID, 前缀JD, SN等, 小米商城和小米有品共用MI前缀(评论互通) comment_id = pw.CharField(max_length=20, primary_key=True) create_time = pw.DateTimeField() # 评论创建时间 content = pw.TextField() # 评论内容 star = pw.SmallIntegerField(constraints=[pw.Check('star between 0 and 5') ]) # 评分星级 after_time = pw.DateTimeField(null=True) # 追评时间 after_content = pw.TextField(null=True) # 追评内容 after_days = pw.SmallIntegerField(null=True) # 追评间隔时间 order_time = pw.DateTimeField(null=True) # 下单时间, 限京东数据源 order_days = pw.SmallIntegerField(null=True) # 从下单到评论的时间(包括物流时间) user_device = pw.CharField( max_length=10, null=True) # 用户设备类型, Android, iOS, other, 限京东和苏宁数据源 # 产品型号信息 product_color = pw.CharField( max_length=4, constraints=[ pw.Check('product_color in ("国风雅灰", "钛银黑", "冰海蓝", "蜜桃金")') ]) # 产品颜色版本 product_ram = pw.CharField(max_length=4, constraints=[ pw.Check('product_ram in ("8GB", "12GB")') ]) # 内存大小 product_rom = pw.CharField( max_length=5, constraints=[pw.Check('product_rom in ("128GB", "256GB")')]) # 储存大小
class Comment(BaseModel): comment_id = pw.CharField(max_length=20, primary_key=True) # 评论ID, 前缀JD, SN source = pw.CharField(max_length=4, constraints=[pw.Check('source in ("京东", "苏宁")')]) is_self = pw.BooleanField() create_time = pw.DateTimeField() # 评论创建时间 content = pw.TextField() # 评论内容 star = pw.SmallIntegerField(constraints=[pw.Check('star between 0 and 5') ]) # 评分星级 after_time = pw.DateTimeField(null=True) # 追评时间 after_content = pw.TextField(null=True) # 追评内容 after_days = pw.SmallIntegerField(null=True) # 追评间隔时间 order_time = pw.DateTimeField(null=True) # 下单时间, 限京东数据源 order_days = pw.SmallIntegerField(null=True) # 从下单到评论的时间(包括物流时间) user_device = pw.CharField( max_length=10, null=True) # 用户设备类型, Android, iOS, other, 限京东和苏宁数据源 color = pw.CharField( max_length=2, constraints=[ pw.Check('color in ("黑色", "白色", "红色", "黄色", "紫色", "绿色")') ]) rom = pw.CharField( max_length=5, constraints=[pw.Check('rom in ("64GB", "128GB", "256GB")')])
class Film(BaseModel): """filmテーブル用モデル.""" film_id = peewee.SmallIntegerField(primary_key=True) title = peewee.CharField(index=True) description = peewee.TextField(null=True) release_year = peewee.DateField(formats="%Y") # 外部キー language = peewee.ForeignKeyField(Language) length = peewee.SmallIntegerField() last_update = peewee.TimestampField() def to_dict(self): return { 'film_id': self.film_id, 'title': self.title, 'description': self.description, 'release_year': self.release_year, 'language': self.language.name, 'length': self.length, 'last_update': self.last_update.isoformat(), } class Meta: db_table = 'film'
class Transaction(pw.Model): id = pw.CharField(max_length=64, primary_key=True) version = pw.SmallIntegerField() block_id = pw.ForeignKeyField( backref="transaction_set", column_name="block_id", field="id", model=migrator.orm["blocks"], ) sequence = pw.SmallIntegerField() timestamp = pw.IntegerField(index=True) sender_public_key = pw.CharField(index=True, max_length=66) recipient_id = pw.CharField(index=True, max_length=66, null=True) type = pw.SmallIntegerField() vendor_field = pw.CharField(max_length=255, null=True) amount = pw.BigIntegerField() fee = pw.BigIntegerField() serialized = pw.BlobField() asset = pw_pext.JSONField(null=True) class Meta: table_name = "transactions" indexes = [( ("sender_public_key", "recipient_id", "vendor_field", "timestamp"), False, )]
class ProcessingInfo(pew.Model): """ ProcessingInfo Database Model """ night = pew.IntegerField() runId = pew.SmallIntegerField() extension = pew.CharField(6) status = pew.SmallIntegerField() # each supported filesystem has a field below isdc = pew.BooleanField(default=False) fhgfs = pew.BooleanField(default=False) bigtank = pew.BooleanField(default=False) class Meta: database = processing_db db_table = "File_Processing_Info" indexes = ((('night', 'runId'), True), ) def getFileSystems(): """ Returns the supported filesystems """ return ['isdc', 'fhgfs', 'bigtank'] def isSupported(fs): """ Checks if the given filesystem is supported """ return fs in ProcessingInfo.getFileSystems()
class Piece(BaseModel): """A model to represent a piece in a game.""" piece_type = EnumField(PieceType) file = pw.SmallIntegerField() rank = pw.SmallIntegerField() side = EnumField(Side) has_moved = pw.BooleanField(default=False) game = pw.ForeignKeyField(model=Game, backref='pieces')
class FuncParam(BaseModel): dim_n = peewee.SmallIntegerField(null=False) interval_a = peewee.DoubleField(null=False) interval_b = peewee.DoubleField(null=False) accuracy_decimals = peewee.SmallIntegerField(null=False) def __str__(self): return ( f'FuncParam: n={self.dim_n} [{self.interval_a}; {self.interval_b}] ' f'q=10^-{self.accuracy_decimals}' )
class FreePeriod(_Model): student = p.ForeignKeyField(Student, related_name='free_periods') period = p.SmallIntegerField() cycle_days = p.SmallIntegerField() semester = p.SmallIntegerField() type = p.SmallIntegerField() def __repr__(self): return 'FreePeriod(student={}, period={}, cycle_days={:08b}, semester={}, type={})'.format( self.student, self.period, self.cycle_days, self.semester, per_type(self.type).name)
class Piece(database.BaseModel): """A model to represent a piece in a game.""" piece_type = EnumField(enums.PieceType) rank = pw.SmallIntegerField() file = pw.SmallIntegerField() side = EnumField(enums.Side) has_moved = pw.BooleanField(default=False) first_move_last_turn = pw.BooleanField(default=False) # For en passant game = pw.ForeignKeyField(model=Game, backref='pieces', on_delete='CASCADE')
class WeatherTable(BaseModel): class Meta: db_table = 'weather' primary_key = peewee.CompositeKey('city_id', 'wdate') city_id = peewee.IntegerField() city = peewee.TextField() city_translit = peewee.TextField() wdate = peewee.DateField() max_temp = peewee.SmallIntegerField() min_temp = peewee.SmallIntegerField() cloudiness = peewee.TextField() precipitations = peewee.TextField(null=True)
class Server(BaseModel): id = pw.IntegerField(primary_key=True) channel = pw.IntegerField(null=False) movie_time = pw.TimeField(null=False, formats="%H:%M", default="12:00") admin_role = pw.TextField(null=False, default="Movie Master") tie_option = pw.TextField(null=False, default="breaker") num_movies_per_vote = pw.SmallIntegerField(null=False, default=8) num_votes_per_user = pw.SmallIntegerField(null=False, default=4) block_suggestions = pw.BooleanField(null=False, default=False) check_movie_names = pw.BooleanField(null=False, default=False) message_timeout = pw.SmallIntegerField(null=False, default=10) class Meta: table_name = "servers"
class Game(BaseModel): """A model to represent a game. The game may be in any of the following states: 1. Open A player is looking for a game matching these specs, but a second player has yet to be found. 2. In progress There are two players in this game, who are currently playing. 3. Completed This game has ended - either there is a winner, or it was a draw. """ host = pw.ForeignKeyField(model=User, backref='games') away = pw.ForeignKeyField(model=User, backref='games', null=True) current_turn = EnumField(Side, default=Side.HOME) _turn_number = pw.SmallIntegerField(default=1, column_name='turn_number') mode = pw.SmallIntegerField(default=1) # only valid value for now starting_time = pw_postgres.IntervalField() # initial timer value time_per_turn = pw_postgres.IntervalField() # time incremement per turn # timers at the start of the current turn, null means starting_time home_time = pw_postgres.IntervalField(null=True) away_time = pw_postgres.IntervalField(null=True) home_offering_draw = pw.BooleanField(default=False) away_offering_draw = pw.BooleanField(default=False) winner = EnumField(Winner, default=Winner.GAME_NOT_COMPLETE) conclusion_type = EnumField(Conclusion, default=Conclusion.GAME_NOT_COMPLETE) opened_at = pw.DateTimeField(default=datetime.datetime.now) last_turn = pw.DateTimeField(null=True) started_at = pw.DateTimeField(null=True) ended_at = pw.DateTimeField(null=True) def __init__(self, *args: typing.Tuple[typing.Any], **kwargs: typing.Dict[str, typing.Any]): """Create a game.""" super().__init__(*args, **kwargs) self.turn_number = TurnCounter(self) self.home_time = self.starting_time self.away_time = self.starting_time def start_game(self, away: User): """Start a game which had no away side.""" self.away = away self.started_at = datetime.datetime.now() self.last_turn = datetime.datetime.now() self.save()
class PdfCreation(DBModel): """The .pdf creation status table""" pdf_creation_id = pw.PrimaryKeyField() # user_id = pw.ForeignKeyField(InternalUser, null=True) datetime_ = pw.DateTimeField(index=True, default=datetime.datetime.now) request_raw = PickledField(null=True, default=None) request_2nd_level = PickledField(null=True, default=None) tex_raw = PickledField(null=True, default=None) pdf_raw = PickledField(null=True, default=None) pdf_signed = PickledField(null=True, default=None) state = pw.SmallIntegerField( index=True, default=REQUEST_RAW ) # see state constants at the beginning of the file locked_timestamp = pw.DateTimeField(index=True, null=True, default=datetime.datetime(1980, 1, 1)) @classmethod @database.atomic() def get_locked_task(self, required_state=None, task_timeout=TIMEOUT): """Gets the PdfCreation locked object with given state""" timeouted_task_time = datetime.datetime.now() - task_timeout task_query = PdfCreation.select().where( (PdfCreation.locked_timestamp <= timeouted_task_time)) if required_state is not None: # if specified, filter along required_state! task_query = task_query.where(PdfCreation.state == required_state) try: task = task_query.get() except pw.DoesNotExist as _: return None # if no task matches the query task.locked_timestamp = datetime.datetime.now() task.save() return task
class PoolTransaction(pw.Model): id = pw.CharField(max_length=64, primary_key=True) version = pw.SmallIntegerField() sequence = pw.SmallIntegerField() timestamp = pw.IntegerField(index=True) sender_public_key = pw.CharField(index=True, max_length=66) recipient_id = pw.CharField(index=True, max_length=66, null=True) type = pw.SmallIntegerField() vendor_field = pw.CharField(max_length=255, null=True) amount = pw.BigIntegerField() fee = pw.BigIntegerField() asset = pw_pext.JSONField(null=True) expires_at = pw.IntegerField(index=True) class Meta: table_name = "pool_transactions"
class Instruction(BaseModel): section = pw.ForeignKeyField(Section, backref='instructions') order = pw.SmallIntegerField() instruction = pw.CharField() class Meta: primary_key = pw.CompositeKey('section', 'order')
class RangoHorario(models.Model): ''' Especifica los rangos horarios en los que la politica esta activa. Atributos ---------- * dia: Dia de la semana, entre 0 y 6 siendo 0 el dia domingo y 6 sabado * hora_inicial: Hora de inicio del rango valido * hora_fin: Hora de fin del rango valido ''' id_rango_horario = models.PrimaryKeyField() politica = models.ForeignKeyField(Politica, related_name='horarios', db_column='id_politica') dia = models.SmallIntegerField() hora_inicial = models.TimeField() hora_fin = models.TimeField() def __contains__(self, item): ''' Devuelve verdadero si la fecha-hora (item) esta dentro del rango. ''' return (item.weekday() == self.dia and self.hora_inicial <= item.time() < self.hora_fin) class Meta: database = db db_table = u'rango_horario'
class User(BaseModel): """User Model for the SQL db""" user_id = pw.UUIDField(primary_key=True, unique=True) username = pw.CharField(unique=True, null=False, max_length=50) password = pw.CharField(null=False, max_length=130) first_name = pw.CharField(null=True, max_length=100) last_name = pw.CharField(null=True, max_length=100) role = pw.SmallIntegerField(null=False, default=0) # 0 - Analysts, 1 - Managers ip_address = pw.CharField(null=True, default=None, max_length=50) last_login_time = pw.DateTimeField(null=True, default=None) created_at = pw.DateTimeField(default=datetime.datetime.now) last_modified_at = pw.DateTimeField(null=True, default=None) """ Meta definition for the table """ class Meta: table_name = SETTINGS['sql']['tables']['users']
class Event(pew.Model): """ Eventlist database model """ night = pew.IntegerField() runId = pew.SmallIntegerField() eventNr = pew.IntegerField() UTC = pew.IntegerField() UTCus = pew.IntegerField() eventType = pew.SmallIntegerField() runType = pew.SmallIntegerField() class Meta: database = processing_db db_table = "EventList" indexes = ((('night', 'runId', 'eventNr'), True), )
class MultipleOption(BaseModelP): question = pw.ForeignKeyField(Question, backref='multiple_option') content = pw.TextField() number = pw.SmallIntegerField() class Meta: indexes = ((('question', 'number'), True),)
class Order(peewee.Model): id = peewee.IntegerField(primary_key=True) order_time = peewee.IntegerField() type = peewee.SmallIntegerField() # 1限价买 2限价卖 3市价买 4市价卖 order_price = peewee.DecimalField(decimal_places=2) # 委托价格 order_amount = peewee.DecimalField(decimal_places=4) # 委托数量 processed_price = peewee.DecimalField(decimal_places=2) # 成交平均价格 processed_amount = peewee.DecimalField(decimal_places=4) # 已经完成的数量 vot = peewee.DecimalField(decimal_places=2) # 交易额 fee = peewee.DecimalField(decimal_places=2) # 手续费 total = peewee.DecimalField(decimal_places=2) # 总交易额(只有人民币交易市场才会返回) status = peewee.SmallIntegerField( ) # 状态 0未成交 1部分成交 2已完成 3已取消 4废弃(该状态已不再使用) 5异常 6部分成交已取消 7队列中 class Meta: database = db
class Socio(peewee.Model): ativo = peewee.SmallIntegerField(null=True) bilhete = peewee.IntegerField(null=True) created_at = peewee.DateTimeField(default=datetime.datetime.now) class Meta: database = mysql_db
class Cat(BaseModel): id = peewee.BigAutoField(unique=True, index=True, primary_key=True) uuid = peewee.CharField(unique=True, index=True, max_length=36) name = peewee.CharField(max_length=256) age = peewee.SmallIntegerField() sex = peewee.BooleanField() breed = peewee.BigIntegerField() health_status = peewee.BigIntegerField() castrated = peewee.BooleanField() vaccinated = peewee.BooleanField() dewormed = peewee.BooleanField() colour = peewee.BigIntegerField() description = peewee.TextField() health_log = peewee.TextField() adoptive = peewee.BooleanField() adopted_by = peewee.CharField(index=True, max_length=36, null=True) pictures = peewee.TextField() created_at = peewee.DateTimeField(default=datetime.datetime.now) updated_at = peewee.DateTimeField() def save(self, *args, **kwargs): self.updated_at = datetime.datetime.now() return super(Cat, self).save(*args, **kwargs) class Meta: table_name = 'cats'
class UserFavorite(pwdb.Model): @unique class Type(IntEnum): POETRY = 0 user_id = pw.BigIntegerField(index=True) poetry_id = pw.IntegerField() type = pw.SmallIntegerField(default=Type.POETRY) class Meta: table_name = "user_favorite" indexes = ((("user_id", "poetry_id"), True), ) @classmethod def list_favorites(cls, user_id, page=1, ipp=10): favs = cls.select().where(cls.user_id == user_id).paginate(page, ipp) poetries = Poetry.select().where( Poetry.id.in_([i.poetry_id for i in favs])) return [i.to_dict() for i in poetries] @classmethod def add_favorite(cls, user_id, poetry_id): cls.create(user_id=user_id, poetry_id=poetry_id)
class Student(_Model): sid = p.BigIntegerField(primary_key=True) grade = p.SmallIntegerField() last_log = p.ForeignKeyField(deferred_log, null=True) def __repr__(self): return 'Student(sid={}, grade={}, last_log={})'.format( self.sid, self.grade, self.last_log.id)
class Reader(db_wrapper.Model): user = peewee.ForeignKeyField(UserAccount, backref='readers') book = peewee.ForeignKeyField(Book, backref='readers') status = peewee.CharField(max_length=20, default='unread') rating = peewee.SmallIntegerField(null=True) added_date = peewee.DateTimeField(default=lambda: arrow.utcnow().naive) read_date = peewee.DateTimeField(null=True) meta = postgres_ext.BinaryJSONField(default=lambda: {})
class Language(BaseModel): """Model for language table""" language_id = peewee.SmallIntegerField(primary_key=True) name = peewee.CharField(max_length=20) last_update = peewee.TimestampField() class Meta: db_table = 'language'
class Transaction(pw.Model): id = pw.CharField(max_length=64, primary_key=True) version = pw.SmallIntegerField() block_id = pw.ForeignKeyField(backref='transaction_set', column_name='block_id', field='id', model=migrator.orm['blocks']) sequence = pw.SmallIntegerField() timestamp = pw.IntegerField(index=True) sender_public_key = pw.CharField(index=True, max_length=66) recipient_id = pw.ForeignKeyField(backref='transaction_set', column_name='recipient_id', field='address', model=migrator.orm['wallets']) type = pw.SmallIntegerField() vendor_field_hex = pw.BlobField(null=True) amount = pw.BigIntegerField() fee = pw.BigIntegerField() serialized = pw.BlobField() class Meta: table_name = "transactions" indexes = [(('sender_public_key', 'recipient_id', 'vendor_field_hex', 'timestamp'), False)]
class Comment(BaseModel): # 评论ID, 前缀JD, SN, YP, YX comment_id = pw.CharField(max_length=20, primary_key=True) source = pw.CharField(max_length=4) is_official = pw.BooleanField() create_time = pw.DateTimeField() # 评论创建时间 content = pw.TextField() # 评论内容 star = pw.SmallIntegerField(constraints=[pw.Check('star between 0 and 5') ]) # 评分星级 spec = pw.CharField(max_length=120) # 产品型号信息 after_time = pw.DateTimeField(null=True) # 追评时间 after_content = pw.TextField(null=True) # 追评内容 after_days = pw.SmallIntegerField(null=True) # 追评间隔时间 order_time = pw.DateTimeField(null=True) # 下单时间, 限京东数据源 order_days = pw.SmallIntegerField(null=True) # 从下单到评论的时间(包括物流时间) user_device = pw.CharField( max_length=10, null=True) # 用户设备类型, Android, iOS, other, 限京东和苏宁数据源
class Game_server(BaseModel): id = pw.AutoField() user_id = pw.ForeignKeyField(User, backref='id', index=True) in_use = pw.SmallIntegerField() ip_string = pw.CharField(max_length=32) port = pw.IntegerField() rcon_password = pw.CharField(max_length=128) display_name = pw.CharField(max_length=32) public_server = pw.BooleanField(default=False)
class Task(BaseModel): """Task class which is used in task manager """ task_id = pw.PrimaryKeyField() datetime = pw.DateTimeField() func_name = pw.CharField() display_name = pw.CharField() status = pw.SmallIntegerField(default=WAITING) args = pw.CharField() important = pw.BooleanField(default=False) message = pw.CharField(default="") @classmethod def create(cls, **query): # replace python list with its json representation if query.get("parameters"): query["args"] = json.dumps(query["parameters"]) return super().create(**query) def get_id(self): """ Returns task id :return: task id """ return self.task_id def get_arguments(self): """ Decode arguments from json :return: arguments to pass in function """ return json.loads(self.args) def run(self): """ Run task function :return: status as number and message as string """ # Save status about current task self.status = RUNNING self.save() event_manager.send_event(f"task_started", self.display_name) # Send event signal about task with its info func = _tasks_functions[self.func_name] # Get function by name # Try to execute task function normally and collect info about it (even if it fails) try: status, message = func(self.get_id(), self.get_arguments()) except Exception as ex: status, message = ERROR, str(ex) # Save status about current task self.status = status self.message = message self.save() # Send event signal about task with its execution result event_manager.send_event(f"task_ended", status, message) # return execution result return status, message