class User(me.Document): telegram_id = me.IntField(primary_key=True) username = me.StringField(min_length=2, max_length=128) first_name = me.StringField(min_length=2, max_length=128) phone_number = me.StringField(max_length=13) email = me.EmailField() user_address = me.StringField(min_length=12, max_length=128) is_block = me.BooleanField(default=False) def __str__(self): return str(self.telegram_id) def formatted_data(self): """ Вывод данных о юзере """ return f'{rca("Id", self.telegram_id, "Отсутствует")}\n{rca("Никнейм", self.username, "Отсутствует")}\n' \ f'{rca("Имя", self.first_name, "Отсутствует")}\n{rca("Телефон", self.phone_number, "Отсутствует")}\n' \ f'{rca("email", self.email, "Отсутствует")}\n{rca("Адресс", self.user_address, "Отсутствует")}' def get_active_cart(self): """ Метод получения корзины, принадлежащий данному юзеру и имеющую статус is_active=True. .first() - выбор первой. Если ее нет, создает и возвращает ее. """ cart = Cart.objects(user=self, is_active=True).first() if not cart: cart = Cart.objects.create( user=self ) return cart return cart def get_order_in_clearance_status(self): """ Метод получения экземпляра класса Order, принадлежащий данному юзеру и имеющую статус in_work_status=False и sent_to_client=False, тоесть не принятой в работу оператору и не отравленную клиенту .first() - выбор первой из списка существующих. Если ее нет, создает и возвращает ее. """ order = Order.objects(user=self, in_work_status=False, sent_to_client=False).first() if not order: order = Order.objects.create( user=self ) return order return order
class PolicyDB(stormbase.StormFoundationDB, stormbase.ContentPackResourceMixin, stormbase.UIDFieldMixin): """ The representation for a policy in the system. Attribute: enabled: A flag indicating whether this policy is enabled in the system. resource_ref: The resource that this policy is applied to. policy_type: The type of policy. parameters: The specification of input parameters for the policy. """ RESOURCE_TYPE = ResourceType.POLICY UID_FIELDS = ['pack', 'name'] name = me.StringField(required=True) ref = me.StringField(required=True) pack = me.StringField( required=False, default=pack_constants.DEFAULT_PACK_NAME, unique_with='name', help_text='Name of the content pack.') description = me.StringField() enabled = me.BooleanField( required=True, default=True, help_text='A flag indicating whether this policy is enabled in the system.') resource_ref = me.StringField( required=True, help_text='The resource that this policy is applied to.') policy_type = me.StringField( required=True, unique_with='resource_ref', help_text='The type of policy.') parameters = me.DictField( help_text='The specification of input parameters for the policy.') meta = { 'indexes': [ {'fields': ['name']}, {'fields': ['resource_ref']}, ] } def __init__(self, *args, **kwargs): super(PolicyDB, self).__init__(*args, **kwargs) self.uid = self.get_uid() self.ref = common_models.ResourceReference.to_string_reference(pack=self.pack, name=self.name)
class Topic(me.Document): meta = {'collection': 'topics'} title = me.StringField(required=True) description = me.StringField(required=True) created_date = me.DateTimeField(required=True, default=datetime.datetime.now) updated_date = me.DateTimeField(required=True, default=datetime.datetime.now) published_date = me.DateTimeField() status = me.StringField(required=True, default='draft', choices=TOPIC_STATUS) """ status: draft, publish, delete """ ip_address = me.StringField(max_length=100, required=True, default='0.0.0.0') author = me.ReferenceField("User", dbref=True, required=True) comments = me.ListField(me.EmbeddedDocumentField(Comment)) tags = me.ListField(me.StringField(required=True), required=True) type = me.StringField(required=True, default='topic', choices=TOPIC_TYPES) comments_disabled = me.BooleanField(default=False, required=True) histories = me.ListField(me.EmbeddedDocumentField(TopicHistory)) def get_comment(self, comment_id): def find_comment(comment_id, comments): # print("comments", len(comments)) # print("comment id:", comment_id) for comment in comments: print("check id:", comment.id) if str(comment.id) == comment_id: print("found") return comment else: if len(comment.replies) > 0: # print("==>", len(comment.replies)) comment = find_comment(comment_id, comment.replies) if comment: return comment # print("check again") return find_comment(comment_id, self.comments)
class PolicyTypeDB(stormbase.StormBaseDB, stormbase.UIDFieldMixin): """ The representation of an PolicyType in the system. Attributes: id: See StormBaseAPI name: See StormBaseAPI description: See StormBaseAPI resource_type: The type of resource that this policy type can be applied to. enabled: A flag indicating whether the policies for this type is enabled. module: The python module that implements the policy for this type. parameters: The specification for parameters for the policy type. """ RESOURCE_TYPE = ResourceType.POLICY_TYPE UID_FIELDS = ['resource_type', 'name'] ref = me.StringField(required=True) resource_type = me.StringField( required=True, unique_with='name', help_text= 'The type of resource that this policy type can be applied to.') enabled = me.BooleanField( required=True, default=True, help_text= 'A flag indicating whether the runner for this type is enabled.') module = me.StringField( required=True, help_text='The python module that implements the policy for this type.' ) parameters = me.DictField( help_text='The specification for parameters for the policy type.') def __init__(self, *args, **kwargs): super(PolicyTypeDB, self).__init__(*args, **kwargs) self.uid = self.get_uid() self.ref = PolicyTypeReference.to_string_reference( resource_type=self.resource_type, name=self.name) def get_reference(self): """ Retrieve reference object for this model. :rtype: :class:`PolicyReference` """ return PolicyTypeReference(resource_type=self.resource_type, name=self.name)
class ActionExecutionSchedulingQueueItemDB(stormbase.StormFoundationDB, stormbase.ChangeRevisionFieldMixin): """ A model which represents a request for execution to be scheduled. Those models are picked up by the scheduler and scheduled to be ran by an action runner. """ RESOURCE_TYPE = ResourceType.EXECUTION_REQUEST UID_FIELDS = ['id'] liveaction_id = me.StringField( required=True, help_text='Foreign key to the LiveActionDB which is to be scheduled') action_execution_id = me.StringField( help_text= 'Foreign key to the ActionExecutionDB which is to be scheduled') original_start_timestamp = ComplexDateTimeField( default=date_utils.get_datetime_utc_now, help_text= 'The timestamp when the liveaction was created and originally be scheduled to ' 'run.') scheduled_start_timestamp = ComplexDateTimeField( default=date_utils.get_datetime_utc_now, help_text='The timestamp when liveaction is scheduled to run.') delay = me.IntField() handling = me.BooleanField( default=False, help_text='Flag indicating if this item is currently being handled / ' 'processed by a scheduler service') meta = { 'indexes': [ { 'fields': ['action_execution_id'] }, { 'fields': ['liveaction_id'] }, { 'fields': ['original_start_timestamp'] }, { 'fields': ['scheduled_start_timestamp'] }, ] }
class TokenDB(stormbase.StormFoundationDB): """ An entity representing an access token. Attribute: user: Reference to the user this token belongs to (username). token: Random access token. expiry: Date when this token expires. service: True if this is a service (system) token. """ user = me.StringField(required=True) token = me.StringField(required=True, unique=True) expiry = me.DateTimeField(required=True) metadata = me.DictField(required=False, help_text='Arbitrary metadata associated with this token') service = me.BooleanField(required=True, default=False)
class Essay(mgng.EmbeddedDocument): timestamp = mgng.DateTimeField() body = mgng.StringField() question = mgng.StringField() # wordfrequency = mgng.DictField() # {String letter: int occurence} # to be calculated when essay loaded, not in DB # meansentencelength = mgng.FloatField() # wordcount = mgng.IntField() # maxwordcount = mgng.IntField() # metapercentile = mgng.IntField() # ^^ some of the expected values ^^ essaystats = mgng.DictField() ispublic = mgng.BooleanField()
class RatingVoteDocument(me.Document): meta = { 'collection': 'rating_votes', 'db_alias': ALIAS_RATING, } name = me.StringField() voter_uid = me.StringField() ratings = me.DictField() contest_uid = me.StringField() is_judge = me.BooleanField() def to_dict(self) -> dict: doc_dict = document_to_dict(self) if hasattr(self, '_id'): doc_dict['timestamp'] = self._id.generation_time() return doc_dict
class nexpose_consoles(mongoengine.Document): #__tablename__="nexpose_consoles" id = mongoengine.IntField(unique=True) enabled = mongoengine.BooleanField(default=True) owner = mongoengine.StringField(null=False) address = mongoengine.StringField(null=False) port = mongoengine.IntField(null=False, default=3780) username = mongoengine.StringField(null=False) password = mongoengine.StringField(null=False) status = mongoengine.StringField(null=False) version = mongoengine.StringField(null=False) cert = mongoengine.StringField(null=False) cached_sites = mongoengine.BinaryField() name = mongoengine.StringField(null=False) created_at = mongoengine.DateTimeField(null=False) updated_at = mongoengine.DateTimeField(null=False)
class Book(me.Document): title = me.StringField(required=True) author = me.StringField(required=True) is_read = me.BooleanField(required=True) created_time = me.DateTimeField(required=True, default=datetime.datetime.now) updated_time = me.DateTimeField(required=True, default=datetime.datetime.now) meta = {'collection': 'books'} def to_dict(self): return dict(id=str(self.id), title=self.title, author=self.author, is_read=self.is_read)
class AccessPoint(mongoengine.Document): """ 权限访问点的数据库模型: pointname: 权限点名称(e.g. leaf.plugins.wxtoken.get) required: 需求的最小权限值 strict: 是否要求仅仅指定权限值的用户可访问 description: 当前权限点的描述 exceptions: 针对某些用户的特例 """ pointname = mongoengine.StringField(primary_key=True) required = mongoengine.IntField(required=True) strict = mongoengine.BooleanField(default=False) description = mongoengine.StringField(default=str) exceptions = mongoengine.ListField( field=mongoengine.LazyReferenceField(User), default=list)
class Project(mongo.Document): project_id = mongo.IntField(required=True, unique=True) title = mongo.StringField(required=True, max_length=200) description = mongo.StringField(required=True, max_length=5000) instructions = mongo.StringField(required=True, max_length=5000) author = mongo.StringField(required=True, max_length=50) image = mongo.StringField(default="") stats = mongo.DictField(required=True) history = mongo.DictField(required=True) remix = mongo.DictField(required=True) engagement = mongo.DictField(default=dict()) validation = mongo.DictField(default=dict()) studio_id = mongo.IntField(default=0) cache_expires = mongo.DateTimeField(default=datetime.now() + timedelta(days=30)) reload_page = mongo.BooleanField(default=False)
class QuizTaken(me.Document): user = me.ReferenceField(User) list_of_questions = me.ListField( me.EmbeddedDocumentField(QuestionsAnswered) ) number_of_questions = me.IntField() correct_answers = me.IntField(default=0) is_done = me.BooleanField(default=False) date_started = me.DateTimeField() date_modified = me.DateTimeField(default=datetime.datetime.now) @property def overall_score(self): return f"{self.correct_answers}/{self.number_of_questions}"
class User(me.Document): chat_id = me.IntField(required=True, unique=True) name = me.StringField(required=True) surname = me.StringField(required=True) username = me.StringField(required=True) interests = me.ListField(default=list()) experience = me.StringField(default="") employment = me.StringField(default="") cv_file_id = me.StringField(default=None) cv_file_name = me.StringField(default=None) apply_counter = me.IntField(default=20) additional_info = me.DictField(default=None) registration_date = me.DateTimeField(required=True) last_update_date = me.DateTimeField(required=True) last_interaction_date = me.DateTimeField(required=True) hr_status = me.BooleanField(default=False)
class Cart(me.Document): customer = me.ReferenceField('Customer') cart_items = me.EmbeddedDocumentListField('CartItem') is_archived = me.BooleanField(default=False) def add_item(self, product): item = CartItem(product=product) if item in self.cart_items: self.cart_items[self.cart_items.index(item)].count += 1 else: self.cart_items.append(item) self.save() def archive(self): self.is_archived = True self.save()
class NewStudentUser(NewBaseUser): role = mongo.StringField(default='student', choices=USER_ROLES) has_usable_password = mongo.BooleanField(default=False) full_name = mongo.StringField(max_length=100) majors = mongo.ListField(mongo.ReferenceField(Major), max_length=3) minors = mongo.ListField(mongo.ReferenceField(Minor), max_length=3) interests = mongo.ListField(mongo.ReferenceField(Tag)) favorited_clubs = mongo.ListField(mongo.StringField(), default=[]) visited_clubs = mongo.ListField(mongo.StringField(), default=[]) club_board = mongo.EmbeddedDocumentField(StudentKanbanBoard) meta = {'auto_create_index': False}
class GroupToRoleMappingDB(stormbase.StormFoundationDB): """ An entity which represents mapping from a remote auth backend group to StackStorm roles. Attribute: group: Name of the remote auth backend group. roles: A reference to the local RBAC role names. description: Optional description for this mapping. """ group = me.StringField(required=True, unique=True) roles = me.ListField(field=me.StringField()) description = me.StringField() enabled = me.BooleanField( required=True, default=True, help_text='A flag indicating whether the mapping is enabled.')
class Event(gj.EmbeddedDocument): id = mongo.StringField(required=True, max_length=100) invite_only = mongo.BooleanField() name = mongo.StringField(required=True, max_length=100) link = RelaxedURLField( null=True, default='' ) # TODO: remove "link" in favor of "links", make mongo migration script for existing events with only one "link" links = mongo.ListField(RelaxedURLField(), default=[], max_length=100) location = mongo.StringField(required=True, default='', max_length=1000) event_start = mongo.DateTimeField(required=True) event_end = mongo.DateTimeField(required=True) description = mongo.StringField(required=True, max_length=1000) tags = mongo.ListField(mongo.ReferenceField(Tag), max_length=100, default=[]) meta = {'auto_create_index': False, 'allow_inheritance': True}
class Feedback(me.EmbeddedDocument): company_name = me.StringField() country = me.StringField() number_of_people = me.StringField() number_of_servers = me.StringField() submitted = me.BooleanField() alternatives = me.StringField() discover = me.StringField() follow_up = me.StringField() # why not bool? hosted = me.ListField() improve = me.StringField() satisfied = me.StringField() def as_dict(self): return json.loads(self.to_json())
class Bill(me.Document): recipient_username = me.StringField(max_length=50, required=True, unique=False) project_id = me.StringField(max_length=20, required=False, unique=False, validation=_not_empty) hw_used = me.DictField() # maps hw_set_name to quantity checked in bill_subtotal = me.DecimalField( min_value=0, force_string=True, precision=2 ) # store as a string, can also force it to round a certain way if needed amount_due = me.DecimalField(min_value=0, force_string=True, precision=2) bill_paid = me.BooleanField(default=False) timestamp = me.IntField(required=True) paid_timestamp = me.IntField(required=False)
class InAppRecommendation(InAppNotification): # Fields specific to recommendations. model_id = me.StringField(required=True) model_output = me.DictField(required=True, default={}) # List of users that applied this recommendation. applied = me.BooleanField(required=True, default=False) def as_dict(self): d = super(InAppRecommendation, self).as_dict() d.update({ 'model_id': self.model_id, 'model_output': self.model_output }) return d
class Member(mongoengine.Document): first_name = mongoengine.StringField(required=True, unique_with="last_name") last_name = mongoengine.StringField(required=True, unique_with="first_name") duplicate_first_name = mongoengine.BooleanField(required=True, default=False) dues = mongoengine.EmbeddedDocumentField(Dues) meta = {'db_alias': 'default', 'collection': 'members'} def __str__(self): return f'{self.first_name} {self.last_name}' def short_name(self): return self.first_name if not self.duplicate_first_name else f'{self.first_name} {self.last_name}'
class Foodstuff(db.Document): title = db.StringField() slug = db.StringField() price = db.FloatField() status = db.StringField(default="pending") #pending, draf, approve servtime = db.StringField() servstatus = db.BooleanField(default=True) categories = db.ListField(db.ReferenceField(Categori, dbref=True)) ingredients = db.ListField(db.EmbeddedDocumentField(Ingredient)) owner = db.ReferenceField(Chef, dbref=True) kitchentool = db.ListField(db.ReferenceField(Kitchentool, dbref=True)) build = db.DateTimeField(default=datetime.utcnow) updated = db.DateTimeField() previews = db.ListField(db.EmbeddedDocumentField(Preview)) meta = {'indexes': ['slug', 'status', 'servtime', 'categories']}
class Book(me.Document): title = me.StringField() published = me.BooleanField() year = me.IntField() # queryset_manager search in all documents @me.queryset_manager def live_books(doc_cls, queryset): # Filtering by condition return queryset.filter(published=True) # It is possible also to override the `objects` method @me.queryset_manager def objects(doc_cls, queryset): # Sort them by default return queryset.order_by('-year')
class PaymentDocument(mongoengine.Document): payment_id = mongoengine.IntField(primary_key=True, required=True) user_id = mongoengine.IntField(required=True) time_created = mongoengine.StringField( default=str(datetime.datetime.now())) account = mongoengine.StringField(max_length=200, required=True) category = mongoengine.StringField(max_length=100, required=True) subcategory = mongoengine.StringField(max_length=100, default="", required=False) contents = mongoengine.StringField(max_length=200, default="", required=False) amount = mongoengine.FloatField(min_value=0, required=True) currency_code = mongoengine.StringField(max_length=10, required=True) is_expense = mongoengine.BooleanField(required=True)
class SensorTypeDB(stormbase.StormBaseDB, stormbase.ContentPackResourceMixin, stormbase.UIDFieldMixin): """ Description of a specific type of a sensor (think of it as a sensor template). Attribute: pack - Name of the content pack this sensor belongs to. artifact_uri - URI to the artifact file. entry_point - Full path to the sensor entry point (e.g. module.foo.ClassSensor). trigger_type - A list of references to the TriggerTypeDB objects exposed by this sensor. poll_interval - Poll interval for this sensor. """ RESOURCE_TYPE = ResourceType.SENSOR_TYPE UID_FIELDS = ['pack', 'name'] name = me.StringField(required=True) ref = me.StringField(required=True) pack = me.StringField(required=True, unique_with='name') artifact_uri = me.StringField() entry_point = me.StringField() trigger_types = me.ListField(field=me.StringField()) poll_interval = me.IntField() enabled = me.BooleanField( default=True, help_text=u'Flag indicating whether the sensor is enabled.') meta = { 'indexes': [ { 'fields': ['name'] }, { 'fields': ['enabled'] }, { 'fields': ['trigger_types'] }, ] + (stormbase.ContentPackResourceMixin.get_indexes() + stormbase.UIDFieldMixin.get_indexes()) } def __init__(self, *args, **values): super(SensorTypeDB, self).__init__(*args, **values) self.ref = self.get_reference().ref self.uid = self.get_uid()
class ZilNode(ModelMixin, mg.Document): meta = {"collection": "zil_nodes"} pub_key = mg.StringField(max_length=128, required=True, unique=True) pow_fee = mg.FloatField(default=0.0) authorized = mg.BooleanField(default=False) email = mg.StringField(max_length=128) def __str__(self): return f"[ZilNode: {self.pub_key}, {self.authorized}]" @classmethod def get_by_pub_key(cls, pub_key, authorized=True): query = mg.Q(pub_key=pub_key) if authorized is not None: query = query & mg.Q(authorized=authorized) return cls.objects(query).first() @classmethod def active_count(cls): from . import pow one_day = datetime.utcnow() - timedelta(days=1) match = { "start_time": { "$gte": one_day, } } group = { "_id": { "pub_key": "$pub_key" }, } return pow.PowWork.aggregate_count(match, group) def works_stats(self): from .pow import PowWork, PowResult working_q = Q(expire_time__gte=datetime.utcnow()) & Q(finished=False) return { "all": PowWork.count(pub_key=self.pub_key), "working": PowWork.count(working_q, pub_key=self.pub_key), "finished": PowWork.count(pub_key=self.pub_key, finished=True), "verified": PowResult.count(pub_key=self.pub_key, verified=True), }
class NormalisedName(mongoengine.EmbeddedDocument): """ Defines a standardised name for a channel or marker and provides method for testing if a channel/marker should be associated to standard Attributes ---------- standard: str, required the "standard" name i.e. the nomenclature we used for a channel/marker in this panel regex_str: str regular expression used to test if a term corresponds to this standard permutations: str String values that have direct association to this standard (comma seperated values) case_sensitive: bool, (default=False) is the nomenclature case sensitive? This would be false for something like 'CD3' for example, where 'cd3' and 'CD3' are synonymous """ standard = mongoengine.StringField(required=True) regex_str = mongoengine.StringField() permutations = mongoengine.StringField() case_sensitive = mongoengine.BooleanField(default=False) def query(self, x: str) -> None or str: """ Given a term 'x', determine if 'x' is synonymous to this standard. If so, return the standardised name. Parameters ----------- x: str search term Returns -------- str or None Standardised name if synonymous to standard, else None """ if self.case_sensitive: if re.search(self.regex_str, x): return self.standard return None if re.search(self.regex_str, x, re.IGNORECASE): return self.standard if self.permutations: for p in self.permutations.split(','): if x == p: return self.standard return None
class SharedSongs(me.Document): record_id = me.UUIDField(default=uuid.uuid4(), required=False) title = me.StringField(required=False) rank = me.IntField(required=False) song_id = me.StringField(required=True) artist = me.StringField(required=False) cover = me.StringField(required=False) album = me.StringField(required=True) playlist_id = me.StringField(required=False) added_to_playlist = me.StringField(required=True) added_by = me.StringField(required=False) created_at = me.DateTimeField(default=datetime.utcnow) api = me.StringField(required=False) link = me.StringField(required=False, default="") is_shared = me.BooleanField(default=False) @staticmethod def fetch_playlist() -> Optional[List[Share]]: get_playlists: List[Playlists] = Playlists.objects(is_active=True) songs: List[Share] = [] for playlist in get_playlists: interface = get_interface(playlist.api) if interface: client = interface client.fetch(playlist_id=playlist.playlist_id) latest: Share = client.get_latest if latest: latest.added_by = playlist.user is_exists = SharedSongs.objects(song_id=latest.song_id, api=latest.api).count() if not is_exists: create = SharedSongs(**asdict(latest)) create.is_shared = True create.save() songs.append(latest) else: raise Exception("Playlist not exist") return songs @staticmethod def get_songs_to_play() -> List[str]: share: List[Share] = SharedSongs.objects().order_by( settings.SHARE_DATE_SORTED)[:settings.QUEUE_LIMIT] songs = [] for song in share: songs.append(f"{song.artist} {song.title}") return songs
class User(mge.Document): email = mge.StringField(max_length=128, primary_key=True) names = mge.ListField(mge.StringField(max_length=16), required=True, max_length=4) surnames = mge.ListField(mge.StringField(max_length=16), required=True, max_length=4) password = mge.StringField(required=True) country = mge.StringField(required=True) city = mge.StringField(required=True) address = mge.StringField(required=True) phone = mge.StringField(required=True) status = mge.BooleanField(default=True) @staticmethod def update_password(email, new_password): user = User.get(email) if user: user.password = new_password user.save() return True return False @staticmethod def get(email): try: query = User.objects.get(email=email, status=True) return query except mge.DoesNotExist: return None @staticmethod def delete_user(email): user = User.get(email) if user: user.status = False user.save() return True return False def __eq__(self, u): self.email = u.email def __str__(self): return 'User_id: {}'.format(self.email)