class ActivityLog(BaseModel): QUERY_EXECUTION = 1 id = peewee.PrimaryKeyField() user = peewee.ForeignKeyField(User) type = peewee.IntegerField() activity = peewee.TextField() created_at = DateTimeTZField(default=datetime.datetime.now) class Meta: db_table = 'activity_log' def to_dict(self): return { 'id': self.id, 'user': self.user.to_dict(), 'type': self.type, 'activity': self.activity, 'created_at': self.created_at } def __unicode__(self): return unicode(self.id)
class TabRating(BaseModel): ''' Rating for App of each user. ''' uid = peewee.CharField(max_length=36, null=False, unique=True, help_text='', primary_key=True) user_id = peewee.CharField( null=False, index=True, max_length=36, help_text='', ) post_id = peewee.CharField( null=False, index=True, max_length=5, help_text='', ) rating = peewee.FloatField(null=False, ) timestamp = peewee.IntegerField(null=False)
class CommentReportLog(pw.Model): rid = pw.ForeignKeyField(db_column="id", model=migrator.orm["sub_post_comment_report"], field="id") action = pw.IntegerField(null=True) desc = pw.CharField(null=True) lid = pw.PrimaryKeyField() link = pw.CharField(null=True) time = pw.DateTimeField() uid = pw.ForeignKeyField(db_column="uid", null=True, model=migrator.orm["user"], field="uid") target = pw.ForeignKeyField(db_column="target_uid", null=True, model=migrator.orm["user"], field="uid") def __repr__(self): return f"<CommentReportLog action={self.action}>" class Meta: table_name = "comment_report_log"
class TabWikiHist(BaseModel): ''' Table for wiki history. ''' uid = peewee.CharField(null=False, index=True, unique=True, help_text='', primary_key=True, max_length=36) title = peewee.CharField( null=False, max_length=255, help_text='', ) wiki_id = peewee.CharField( null=False, max_length=36, help_text='', ) user_name = peewee.CharField() cnt_md = peewee.TextField() time_update = peewee.IntegerField()
class TabPost2Tag(BaseModel): ''' Table of tag to the post. ''' uid = peewee.CharField( null=False, index=True, unique=True, primary_key=True, max_length=36, help_text='', ) tag_id = peewee.CharField( null=False, max_length=4, help_text='', ) post_id = peewee.CharField( null=False, max_length=5, help_text='', ) order = peewee.IntegerField()
class Talk(pw.Model): id = pw.AutoField() description = pw.TextField() duration = pw.IntegerField() event = pw.ForeignKeyField( backref='talks', column_name='event_id', field='id', model=migrator.orm['event'] ) hall = pw.TextField(null=True) published = pw.BooleanField() start = pw.DateTimeField(null=True) title = pw.TextField() user = pw.ForeignKeyField( backref='talks', column_name='user_id', field='id', model=migrator.orm['users'] ) class Meta: table_name = "talk"
class DatabaseNamespaceModel(DatabaseBaseModel): """Represents a namespace hierarchy""" name = pw.CharField() level = pw.IntegerField() parent = pw.ForeignKeyField("self", backref="children", null=True) @staticmethod def db_create(namespace: Sequence[str]) -> "DatabaseNamespaceModel": """Create a namespace hierarchy in the database""" parent = None for level, node in enumerate(namespace): try: db_node = DatabaseNamespaceModel.get(name=node, level=level, parent=parent) except pw.DoesNotExist: db_node = DatabaseNamespaceModel.create(name=node, level=level, parent=parent) parent = db_node return db_node
class CommandQueue(peewee.Model): """ """ WAITING = 0 SUBMITTED = 4 node_id = peewee.ForeignKeyField(Node, backref='commands') status = peewee.IntegerField() command = peewee.TextField() created_at = peewee.DateField(default=datetime.date.today) downloaded_at = peewee.DateField(default=datetime.date.today) def statusName(t): if t == CommandQueue.WAITING: return "Waiting" elif t == CommandQueue.SUBMITTED: return "Submited" else: return "Done" class Meta: database = Database()._database
class Task(BaseModel): title = pw.CharField(max_length=100) date = pw.DateField() priority = pw.IntegerField(default=0) project = pw.ForeignKeyField(Project) # Получение задачи с фильтрацией на текущего пользователя @classmethod def get_item(cls, task_id, current_user_id): return Task.select() \ .where(Task.id == task_id) \ .join(Project) \ .where(Project.user == current_user_id) # Получение списка задач с фильтрацией на текущего пользователя @classmethod def get_list(cls, current_user_id=1, params=None, page=1, paginate_by=1, ordered='id'): tasks = [] if params: tasks = Task.filter(**params) \ .join(Project) \ .where(Project.user == current_user_id) \ .order_by(ordered)\ .paginate(page=int(page), paginate_by=paginate_by) else: tasks = Task.select() \ .join(Project) \ .where(Project.user == current_user_id) \ .order_by(ordered)\ .paginate(page=int(page), paginate_by=paginate_by) # if ordered: # tasks = tasks.order_by(ordered) return tasks
class MessageBlob(MyModel): """ Represents an encrypted message blob in the blob store. This table exists to facilitate a single blob being used by multiple messages, as in a broadcast or a group chat. """ path = pw.CharField(unique=True, verbose_name='Path to file in blob store', help_text='Relative path to content which can be '+\ 'decrypted with the session key.') size = pw.IntegerField(index=True, verbose_name='File size', help_text='Size of referenced file, in bytes. '+\ 'Together with the upload time, used to'+\ 'determine which files and messages to delete.') @classmethod def delete_orphans(cls): ''' Delete orphaned blobs. Return (number of deleted files, total size). Should be run periodically to clear disk space. ''' query = cls.select().\ # for every row in this table, join(Message, pw.JOIN.LEFT).\ # add the message referencing it where(Message.id.is_null()) # and return ones that have no match count = 0 size = 0 for row in query: # TODO: remove the file count += 1 size += row.size row.delete_instance() return count, size
class Posts(Model): id = peewee.IntegerField() question_id = peewee.IntegerField() user_id = peewee.IntegerField() type = peewee.IntegerField() username = peewee.CharField(max_length=200) content = peewee.TextField() belong_to_post_id = peewee.IntegerField() parent_post_id = peewee.IntegerField() title = peewee.CharField(max_length=255) date_created = peewee.DateTimeField( formats='%Y-%m-%d %H:%M:%S', default=datetime.now ) class Meta: database = db db_table = 'posts'
class Channel(BaseModel): telegram_id = peewee.BigIntegerField(default=0, unique=True) title = peewee.CharField() username = peewee.CharField(null=True) photo = peewee.CharField(null=True) description = peewee.TextField(null=True) cost = peewee.IntegerField(default=0) likes = peewee.IntegerField(default=0) members = peewee.IntegerField(default=0) verified = peewee.BooleanField(default=False) category = peewee.ForeignKeyField(Category, null=True) # Attributes bellow are unconfirmed and probably useless language = peewee.CharField(null=True) members_growth = peewee.IntegerField(default=0) views = peewee.IntegerField(default=0) views_growth = peewee.IntegerField(default=0) vip = peewee.BooleanField(default=False)
class Member(peewee.Model): chat_id = peewee.IntegerField() user = peewee.ForeignKeyField(User, backref='members') last_activity = peewee.DateField(default=datetime.datetime.now) class Meta: table_name = 'Members' database = db primary_key = peewee.CompositeKey('chat_id', 'user') indexes = ((('chat_id', 'user_id'), True), ) @classmethod def upsert(cls, chat_id, user_obj): user = User.upsert_and_get(user_obj) # upsert: http://docs.peewee-orm.com/en/latest/peewee/querying.html#upsert cls.replace(chat_id=chat_id, user=user, last_activity=datetime.datetime.now()).execute() @classmethod def upsert_many(cls, chat_id, users): now = datetime.datetime.now() for usert_object in users: user = User.upsert_and_get(usert_object) # now upsert the new member cls.replace(chat_id=chat_id, user=user, last_activity=now).execute() @classmethod def get_active(cls, chat_id, days_delta=21, limit=200): now = datetime.datetime.now() delta = datetime.timedelta(days=days_delta) active_from = now - delta return (cls.select().join(User, on=(cls.user == User.user_id)).where( cls.chat_id == chat_id, cls.last_activity > active_from).order_by( cls.last_activity.desc()).limit(limit))
class TabApp_yunsuan(BaseModel): uid = peewee.CharField(max_length=4, null=False, unique=True, help_text='', primary_key=True) title = peewee.CharField(null=False, help_text='标题', ) keywords = peewee.CharField(null=True, default='') desc = peewee.CharField(null=True, default='') industry = peewee.CharField(default='') date = peewee.DateTimeField(null=False, help_text='显示出来的日期时间') run_count = peewee.IntegerField(null=False, default=0, help_text='运行次数') view_count = peewee.IntegerField(null=False, default=0, help_text='查看次数') run_time = peewee.IntegerField(null = False, default = 0, help_text='上次运行时间') update_time = peewee.IntegerField(null=False, default=0, help_text='更新时间') create_time = peewee.IntegerField(null=False, default=0, help_text='创建时间') type = peewee.IntegerField(null=False, default=1) html_path = peewee.CharField(default='') cnt_md = peewee.TextField(null = True) cnt_html = peewee.TextField(null = True) # lon = peewee.FloatField() # lat = peewee.FloatField() # zoom_current = peewee.IntegerField() # zoom_max = peewee.IntegerField() # zoom_min = peewee.IntegerField() time_update = peewee.IntegerField(null = False, default = 0)
class Note(peewee.Model): server = peewee.ForeignKeyField(DBServer, related_name="notes") message_id = peewee.BigIntegerField() status = peewee.IntegerField(default=NOTE_OPEN) text = peewee.CharField(max_length=1000) date = peewee.DateTimeField(default=datetime.datetime.now) submitter_name = peewee.CharField() submitter_id = peewee.BigIntegerField() note_id = peewee.BigIntegerField() @property def open(self): return self.status == NOTE_OPEN @property def closed(self): return self.status == NOTE_CLOSED @property def resolved(self): return self.status == NOTE_RESOLVED class Meta: database = database
class EHHInfo(ScanTable): ''' EHH scores for a given core locus within a given population ''' population_set = pw.ForeignKeyField(PopulationSet) core_locus = pw.ForeignKeyField(LocusInfo) pos_bp_delta = pw.IntegerField() map_pos_cm_delta = pw.DoubleField() EHH_ones = pw.DoubleField() EHH_zeros = pw.DoubleField() EHH = pw.DoubleField() class Meta(object): indexes = ((('population_set', 'core_locus', 'pos_bp_delta'), True), ) def __str__(self): return ",".join([ str(self.core_locus), str(self.population_set), str(self.EHH_ones), str(self.EHH_zeroes), str(self.EHH) ])
class Image(BaseModel): class Status(Enum): UNVERIFIED = 0 PASSED = 1 FAILED = 2 order_id = pw.ForeignKeyField(Order, backref="pictures") path = pw.CharField() status = pw.IntegerField(default=Status.UNVERIFIED.value) @hybrid_property def pict_url(self): # Returns full url of image return f"{AWS_DOMAIN}/{self.path}" def pass_mod(self): self.status = Image.Status.PASSED.value def fail_mod(self): self.status = Image.Status.FAILED.value @pysnooper.snoop('log.txt') def moderate(self): models = [app.models.get('cigarettes'), app.models.get('moderation')] errors = [] for model in models: res = {} response = model.predict_by_url( url=f"{AWS_DOMAIN}/{self.path}") results = response['outputs'][0]['data']['concepts'] for i, v in enumerate(results): if results[i]['value'] > 0.6 and results[i]['name'] not in 'safe': res['error'] = results[i]['name'] errors.append(res) return errors
class AvailableActions(peewee.Model): user_id = peewee.IntegerField(primary_key=True) actions = peewee.CharField() class Meta: database = db def get_actions(self, user_id): try: action_list = self.get(self._schema.model.user_id == user_id) return action_list except self.DoesNotExist: action_list = self.create(user_id=user_id, actions='[]') return action_list def update_actions(self, user_id, action_list): user_actions = self.get_actions(user_id) user_actions.actions = json.dumps(action_list, ensure_ascii=False) user_actions.save() def is_action_available(self, user_id, action): user_actions = self.get_actions(user_id) available_actions = json.loads(user_actions.actions) return action in available_actions
class Transaction(BaseModel): class Types: debit = 'debit' credit = 'credit' tr_type = peewee.CharField(max_length=7, choices=[Types.debit, Types.credit]) tr_hash = peewee.CharField(max_length=200, default='') address_from = peewee.CharField(max_length=100) address_to = peewee.CharField(max_length=100) amount = peewee.DecimalField() confirmation_counts = peewee.IntegerField(default=0) processed_at = peewee.DateTimeField(default=None, null=True) def __str__(self): return "{id}: {addr_from} > {addr_to} | processed_at={processed_at} (conf: {conf_cnt})".format( id=self.id, addr_from=self.address_from, addr_to=self.address_to, conf_cnt=self.confirmation_counts, processed_at=self.processed_at) class Meta: db_table = 'bot_transaction'
class Subscription(BaseModel): user = pw.ForeignKeyField(User, backref="subscription", on_delete="CASCADE", unique=False) name = pw.CharField(unique=False) description = pw.CharField(unique=False, null=True) amount = pw.DecimalField(max_digits=15, decimal_places=2, null=True) payment_date = pw.DateField(unique=False) subs_type = pw.CharField(unique=False) #Daily, Weekly, Monthly, Yearly frequency = pw.IntegerField(unique=False) paid = pw.BooleanField(default=False) next_payment = pw.DateField(unique=False) due = pw.BooleanField(default=False) def validate(self): if self.subs_type == "daily": self.next_payment = add_days(self.payment_date, self.frequency) elif self.subs_type == "weekly": self.next_payment = add_weeks(self.payment_date, self.frequency) elif self.subs_type == "monthly": self.next_payment = add_months(self.payment_date, self.frequency) elif self.subs_type == "yearly": self.next_payment = add_years(self.payment_date, self.frequency)
class FileData(p.Model): chunk_num = p.IntegerField() # what chunk number is this timestamp = p.DateTimeField(default=datetime.datetime.now, null=False) chunk_data = p.BlobField() meta_data = p.ForeignKeyField(FileMeta) class Meta: database = apfell_db def to_json(self): r = {} for k in self._data.keys(): try: if k == 'meta_data': r[k] = getattr(self, k).id elif k != 'chunk_data': r[k] = getattr(self, k) except: r[k] = json.dumps(getattr(self, k)) r['timestamp'] = r['timestamp'].strftime('%m/%d/%Y %H:%M:%S') return r def __str__(self): return str(self.to_json())
class ReleaseInfo(peewee.Model): rid = peewee.TextField() is_external = peewee.BooleanField(default=False) is_edited = peewee.BooleanField(default=False) artist = peewee.TextField() title = peewee.TextField() genres = peewee.TextField() released = peewee.IntegerField() cover_image = peewee.TextField(null=True) # filename of cover image def get_tracks(self): return TrackInfo.select().where(TrackInfo.release == self).objects() def get_images(self): return ImageInfo.select().where(ImageInfo.release == self).objects() def get_genres(self): return self.genres.split(";") class Meta: database = Database.get()
class TabLog(BaseModel): ''' 用户访问行为记录 ''' uid = peewee.CharField( null=False, index=True, unique=True, primary_key=True, max_length=36, ) post_id = peewee.CharField( null=False, max_length=36, help_text='', ) user_id = peewee.CharField( null=False, index=True, max_length=36, help_text='', ) time_create = peewee.IntegerField(null=False, default=0) kind = peewee.CharField(null=False)
class FlrMenu(BaseModel): name = pw.CharField() section_id = pw.ForeignKeyField(FlrMenuSection, backref="menus") groups = pw.ManyToManyField(Registry["FlrGroup"]) sequence = pw.IntegerField(default=1) @classmethod def get_menus(cls): user = Registry["FlrUser"].get_by_id(request.uid) user_groups = set([x.id for x in user.groups]) result = [] for section in FlrMenuSection.select().order_by( FlrMenuSection.sequence): section_obj = {'id': section.id, 'name': section.name, 'menus': []} for menu in section.menus.order_by(FlrMenu.sequence): menu_groups = [g.id for g in menu.groups] if not menu.groups or user_groups.intersection(menu_groups): section_obj["menus"].append({ "id": menu.id, "name": menu.name }) if section_obj["menus"]: result.append(section_obj) return result
class RealtyItem(BaseModel): apiId = peewee.CharField() originalId = peewee.CharField() origin = peewee.CharField() url = peewee.CharField() time_appeared = peewee.DateField() time_disappeared = peewee.DateField(null=True) last_update = peewee.DateField(null=True) title = peewee.CharField() price = peewee.IntegerField() phone = peewee.CharField(null=True) contact_person = peewee.CharField() contact_type = peewee.CharField( ) # Частное лицо", "Агентство" или "Частное лицо (фильтр)" city = peewee.CharField() region = peewee.CharField() subway = peewee.CharField() address = peewee.CharField() description = peewee.CharField() record_type = peewee.CharField() # Продам, Сдам, Куплю или Сниму images = peewee.CharField() params = peewee.CharField()
class LogoAnnotation(BaseModel): image_prediction = peewee.ForeignKeyField( ImagePrediction, null=False, backref="logo_detections" ) index = peewee.IntegerField(null=False, constraints=[peewee.Check("index >= 0")]) bounding_box = BinaryJSONField(null=False) score = peewee.FloatField(null=False) annotation_value = peewee.CharField(null=True, index=True) annotation_value_tag = peewee.CharField(null=True, index=True) taxonomy_value = peewee.CharField(null=True, index=True) annotation_type = peewee.CharField(null=True, index=True) username = peewee.TextField(null=True, index=True) completed_at = peewee.DateTimeField(null=True, index=True) nearest_neighbors = BinaryJSONField(null=True) class Meta: constraints = [peewee.SQL("UNIQUE(image_prediction_id, index)")] def get_crop_image_url(self) -> str: base_url = ( settings.OFF_IMAGE_BASE_URL + self.image_prediction.image.source_image ) y_min, x_min, y_max, x_max = self.bounding_box return f"https://robotoff.openfoodfacts.org/api/v1/images/crop?image_url={base_url}&y_min={y_min}&x_min={x_min}&y_max={y_max}&x_max={x_max}"
class Patient(peewee.Model): patient_id = peewee.PrimaryKeyField() patient_firstname = peewee.CharField() patient_lastname = peewee.CharField() patient_email = peewee.CharField() patient_address_1 = peewee.CharField() patient_address_2 = peewee.CharField() patient_postalcode = peewee.CharField() patient_province = peewee.CharField() phone_no = peewee.CharField() patient_age = peewee.CharField() patient_height = peewee.CharField() patient_weight = peewee.CharField() doctor_id = peewee.ForeignKeyField(Doctor, to_field="doctor_id") status = peewee.IntegerField(default=1) def save(self, *args, **kwargs): self.modify_date = datetime.datetime.strptime( datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S') return super(Patient, self).save(*args, **kwargs) class Meta: database = DatabaseConfig.db
class ATTACKId(p.Model): t_num = p.IntegerField(null=False) name = p.CharField(null=False) cmd = p.ForeignKeyField(Command, null=False) task = p.ForeignKeyField(Task, null=True) # optionally specify which specific task is a certain att&ck ID class Meta: indexes = ((('t_num', 'cmd'), True),) database = apfell_db def to_json(self): r = {} for k in self._data.keys(): try: if k == 'cmd': r[k] = getattr(self, k).cmd else: r[k] = getattr(self, k) except: r[k] = json.dumps(getattr(self, k)) return r def __str__(self): return str(self.to_json())
class Service(ConnectionModel): name = orm.CharField(max_length=255) item = orm.ForeignKeyField(Item, related_name='items') pub_date = orm.DateTimeField(default=datetime.datetime.now) allowed_users = ManyToManyField(User, related_name='allowed_services') # Password username = orm.CharField(max_length=255, null=True) password = orm.CharField(max_length=255, null=True) url = orm.CharField(max_length=255, null=True) port = orm.IntegerField(null=True) extra = orm.TextField(null=True) # SSH ssh_title = orm.CharField(max_length=255, null=True) ssh_public = orm.TextField(null=True) ssh_private = orm.TextField(null=True) # SSL ssl_title = orm.CharField(max_length=255, null=True) ssl_filename = orm.CharField(max_length=255, null=True) # Other other = orm.TextField(null=True)
class DataFlagVote(base_model): """ A Vote that resulted in the translation of opinions to flags. Attributes ---------- time : float Unix time at vote creation. mode : str Voting mode name. They are implemented in `chimed.dataflag.opinion.vote`. client : DataFlagClient Client used to vote. lsd : int Local Sidereal Day this vote is about. """ max_len_mode_name = 32 time = pw.FloatField() mode = pw.CharField(max_length=max_len_mode_name) client = pw.ForeignKeyField(DataFlagClient) revision = pw.ForeignKeyField(DataRevision, backref="votes") flag = pw.ForeignKeyField(DataFlag, backref="vote", null=True) lsd = pw.IntegerField()