class Project(Document): meta = {'collection': 'projects'} pid = SequenceField(required=True, primary_key=True, unique=True) name = StringField(required=True) descr = StringField(default="No Description") url = StringField(default="") team_ids = ListField(IntField(), default=[]) deliverable_ids = ListField(IntField(), default=[]) def __init__(self, *args, **kwargs): Document.__init__(self, *args, **kwargs) if 'pid' in kwargs: self.pid = kwargs['pid'] if 'name' in kwargs: self.name = kwargs['name'] if 'descr' in kwargs: self.descr = kwargs['descr'] if 'url' in kwargs: self.url = kwargs['url'] if 'team_ids' in kwargs: self.team_ids = kwargs['team_ids'] if 'deliverable_ids' in kwargs: self.deliverable_ids = kwargs['deliverable_ids'] @staticmethod def init_project(name, url, descr): pid = Project.objects.count() + 1 return Project(pid=pid, name=name, url=url, descr=descr)
class Team(Document): meta = {'collection': 'teams'} tid = SequenceField(required=True, unique=True, primary_key=True) name = StringField(required=True) user_ids = ListField(IntField(), default=[]) message_ids = ListField(IntField(), default=[]) task_ids = ListField(IntField(), default=[]) meeting_ids = ListField(IntField(), default=[]) def __init__(self, *args, **kwargs): Document.__init__(self, *args, **kwargs) if 'tid' in kwargs: self.tid = kwargs['tid'] if 'name' in kwargs: self.name = kwargs['name'] if 'user_ids' in kwargs: self.user_ids = kwargs['user_ids'] if 'message_ids' in kwargs: self.message_ids = kwargs['message_ids'] if 'task_ids' in kwargs: self.task_ids = kwargs['task_ids'] if 'meeting_ids' in kwargs: self.meeting_ids = kwargs['meeting_ids'] @staticmethod def init_team(name): tid = Team.objects.count() + 1 return Team(tid=tid, name=name)
class CommodityRequest(Document): meta = {'collection': 'commodity_request'} request_id = SequenceField() commodity = ReferenceField(Commodity) public_id = StringField(required=True) address = StringField(default=True) create_date = StringField( default=datetime.now().strftime("%-d/%B/%Y %I:%M:%S"))
class Commodity(Document): meta = {'collection': 'commodity'} commodity_id = SequenceField() name = StringField(required=True) brand = StringField(default="NA") public_id = StringField() create_date = StringField( default=datetime.now().strftime("%-d/%B/%Y %I:%M:%S"))
class Store(Document): meta = {'collection': 'store'} store_id = SequenceField() name = StringField(required=True) address = StringField(default="NA") public_id = StringField() create_date = StringField( default=datetime.now().strftime("%-d/%B/%Y %I:%M:%S"))
class Question(EmbeddedDocument): """docstring for Answers.""" QID = SequenceField() question_text = StringField(max_length=600, required=True) # options = ReferenceField('Options', reverse_delete_rule=0) options = ListField(EmbeddedDocumentField(Options)) answer = StringField(max_length=200, required=True)
class Comments(Document): meta = {'collection': 'comments'} comment_id = SequenceField() commodity = ReferenceField(Commodity, required=True) store = ReferenceField(Store, required=True) public_id = StringField(required=True) is_available = BooleanField(default=True) create_date = StringField( default=datetime.now().strftime("%-d/%B/%Y %I:%M:%S"))
class User(db.DynamicDocument): """ User Model for storing user related details """ id = SequenceField(required=True, primary_key=True) user_name = StringField(min_length=4) password = StringField(required=True) email = EmailField(required=True, unique=True) phone = StringField(min_length=10, required=True, unique=True) registered_on = DateTimeField(default=datetime.datetime.now) def clean(self): self.password = bcrypt.generate_password_hash( self.password, app.config.get('BCRYPT_LOG_ROUNDS')).decode() meta = {"indexes": ["email", "phone"], "ordering": ["-registered_on"]} @staticmethod def encode_auth_token(user_id): """ Generates the Auth Token :return: string """ user_id = str(user_id) try: payload = { 'exp': datetime.datetime.utcnow() + datetime.timedelta(days=5, seconds=5), 'iat': datetime.datetime.utcnow(), 'sub': user_id } return jwt.encode(payload, app.config.get('SECRET_KEY'), algorithm='HS256') except Exception as e: return e @staticmethod def decode_auth_token(auth_token): """ Validates the auth token :param auth_token: :return: integer|string """ try: payload = jwt.decode(auth_token, app.config.get('SECRET_KEY')) is_blacklisted_token = BlacklistToken.check_blacklist(auth_token) if is_blacklisted_token: return 'Token blacklisted. Please log in again.' else: return payload, User.objects.get(id=payload['sub']) except jwt.ExpiredSignatureError: return 'Signature expired. Please log in again.' except jwt.InvalidTokenError: return 'Invalid token. Please log in again.'
class CaseDetails(DynamicDocument): lnkr_query_id = SequenceField() lnkr_user_id = IntField() platform = StringField() report_type = StringField() title = StringField() creation_date = DateTimeField() status = StringField() input_args = EmbeddedDocumentField(InputArgs, default=InputArgs()) file_name = StringField()
class Users(Document): meta = {'collection': 'users'} user_id = SequenceField() public_id = StringField(required=True) name = StringField(required=True) email = EmailField(required=True) password = StringField(required=True) address = StringField() profile_pic = StringField() create_date = StringField( default=datetime.now().strftime("%-d/%B/%Y %I:%M:%S"))
class TodoInfoModel(BaseDocument): meta = {"collection": "todo_info"} no = SequenceField(collection_name="todo_info") title = StringField(required=True) main_cate = StringField(required=True) sub_cate = StringField() status = StringField() desc = StringField() star = BooleanField(default=False) due_date = StringField() due_time = StringField()
class Profile(BDocument): id = SequenceField(primary_key=True) name = StringField(required=True, unique=True) is_root = BooleanField(default=False) default_state = StringField() permissions = MapField(EmbeddedDocumentField(Resource)) def is_allowed(self, resource, action): if not self.is_root: if resource in self.permissions and not self.permissions[resource].is_all: return action in self.permissions[resource].actions else: return resource in self.permissions else: return True
class Cafeteria(db.DynamicDocument): id = SequenceField(required=True, primary_key=True) cafe_owner = ReferenceField(User) cafe_name = StringField(min_length=4) city = StringField(required=True) address = StringField(required=True) pincode = IntField(required=True) cafe_start_time = IntField(min_value=0, max_value=1440, required=True) cafe_close_time = IntField(min_value=0, max_value=1440, required=True) registered_on = DateTimeField(default=datetime.datetime.now) def clean(self): opens_at = self.cafe_start_time closes_at = self.cafe_close_time if closes_at < opens_at or not isinstance( closes_at, int) or not isinstance(opens_at, int): raise ValidationError("Invalid Opening and closing hours")
class Item(db.DynamicDocument): id = SequenceField(required=True, primary_key=True) cafe = ReferenceField(Cafeteria) item_name = StringField(required=True) item_available_hours = ListField(DictField()) def clean(self): item_available_hours = self.item_available_hours if len(item_available_hours) != 7: raise ValidationError( "Total week days not matching. Need to fill for all week") for day_opening_timings in item_available_hours: opens_at = day_opening_timings.get("opens_at") closes_at = day_opening_timings.get("closes_at") if closes_at < opens_at or not isinstance( closes_at, int) or not isinstance(opens_at, int): raise ValidationError("Invalid Opening and closing hours")
class BlacklistToken(db.DynamicDocument): """ Token Model for storing JWT tokens """ id = SequenceField(required=True, primary_key=True) token = StringField(max_length=500, required=True, unique=True) blacklisted_on = DateTimeField(default=datetime.datetime.now) def __repr__(self): return '<id: token: {}'.format(self.token) @staticmethod def check_blacklist(auth_token): # check whether auth token has been blacklisted res = BlacklistToken.objects(token=str(auth_token)).first() if res: return True else: return False
class MnUser(BDocument): id = SequenceField(primary_key=True) username = StringField(required=True) password = StringField(required=True) email = StringField(default=None) last_login_at = DateTimeField(default=None) is_active = BooleanField(default=True) is_special = BooleanField(default=False) profile = ReferenceField(Profile) USERNAME_FIELD = 'username' REQUIRED_FIELDS = () meta = { "collection": "user", 'indexes': [ {'fields': ['username'], 'unique': True, 'sparse': True} ] } def __unicode__(self): return self.username @staticmethod def is_anonymous(): return False @staticmethod def is_authenticated(): return True def set_password(self, raw_password): self.password = make_password(raw_password) return self.save() def check_password(self, raw_password): return check_password(raw_password, self.password) @classmethod def create_user(cls, username, password): user = cls(username=username) return user.set_password(password)
class User(Document, CommonEqualityMixin, UserMixin): """Base User Class. Inherited by Student and Instructor Contains base functionality and fields for both classes """ meta = {'allow_inheritance': True, 'collection': 'users'} uid = SequenceField(primary_key=True, required=True, unique=True) first_name = StringField(required=True) last_name = StringField(required=True) username = StringField(required=True) type = StringField(required=True, max_length=1, choices=('u', 'p')) message_ids = ListField(IntField(), default=[]) encrypt_pw = StringField(required=True) def __init__(self, *args, **kwargs): Document.__init__(self, *args, **kwargs) if 'uid' in kwargs: self.uid = kwargs['uid'] if 'first_name' in kwargs: self.first_name = kwargs['first_name'] if 'last_name' in kwargs: self.last_name = kwargs['last_name'] if 'username' in kwargs: self.username = kwargs['username'] if 'type' in kwargs: self.type = kwargs['type'] if 'message_ids' in kwargs: self.message_ids = kwargs['message_ids'] if 'encrypt_pw' in kwargs: self.encrypt_pw = kwargs['encrypt_pw'] @property def full_name(self): return self.first_name + " " + self.last_name def verify_password(self, password): return check_password_hash(self.encrypt_pw, password) def get_id(self): return self.uid
class Assignment(Document): # Set the collection name used in the database meta = {'allow_inheritance': True, 'collection': 'assignments'} aid = SequenceField(required=True, primary_key=True, unique=True) class_id = IntField(required=True) due = DateTimeField(required=True) description = StringField() def __init__(self, *args, **kwargs): Document.__init__(self, *args, **kwargs) if 'aid' in kwargs: self.aid = kwargs['aid'] if 'class_id' in kwargs: self.class_id = kwargs['class_id'] if 'due' in kwargs: self.due = kwargs['due'] if 'description' in kwargs: self.description = kwargs['description']
class BasicMessage(Document, CommonEqualityMixin): meta = {'allow_inheritance': True, 'collection': 'messages'} mid = SequenceField(required=True, primary_key=True, unique=True) text = StringField(required=True) sender_id = IntField(required=True) seen = BooleanField(default=False) def __init__(self, *args, **kwargs): Document.__init__(*args, **kwargs) if 'mid' in kwargs: self.mid = kwargs['mid'] if 'text' in kwargs: self.text = kwargs['text'] if 'sender' in kwargs: self.sender = kwargs['sender'] if 'seen' in kwargs: self.seen = kwargs['seen'] def mark_as_seen(self): self.seen = True
class UserLocation(Document): email = EmailField(required=True, unique=True, max_length=200) name = StringField(required=True, max_length=200) location = PointField(required=True) mappoint_id = SequenceField(required=True)
class BDocument(Document): DELETING_LEVEL = None DELETING_CHILDS = () id = SequenceField(primary_key=True) created_at = DateTimeField(default=None) updated_at = DateTimeField(default=None) deleted_at = DateTimeField(default=None) is_deleted = BooleanField(default=False) deleting_level = IntField(default=None) is_system = BooleanField(default=None) # owner = ReferenceField('Staff', null=True) # 2017-09-24 _serializer = None default_serializer = None all = BQuerySetManager() objects = BQuerySetManager() meta = {'abstract': True} def __eq__(self, other): return getattr(self, 'id', None) == getattr(other, 'id', None) def __new__(cls, **kwargs): cls._fields['id'].owner_document = cls if cls.default_serializer is None: cls.default_serializer = cls.__name__ + "Serializer" """ signals.post_init.connect(document.post_init, sender=cls) signals.post_init.connect(document.post_init, sender=cls) signals.pre_save.connect(document.pre_save, sender=cls) signals.pre_save_post_validation.connect(document.pre_save_post_validation, sender=cls) signals.post_save.connect(document.post_save, sender=cls) signals.pre_delete.connect(document.pre_delete, sender=cls) signals.post_delete.connect(document.post_delete, sender=cls) signals.pre_bulk_insert.connect(document.pre_bulk_insert, sender=cls) signals.post_bulk_insert.connect(document.post_bulk_insert, sender=cls) signals.pre_init.connect(document.pre_init, sender=cls) """ return super(BDocument, cls).__new__(cls) def save(self, **kwargs): if self.created_at is None: self.created_at = datetime.now() else: self.updated_at = datetime.now() return super(BDocument, self).save(**kwargs) def erase(self, signal_kwargs=None, **write_concern): super(BDocument, self).delete(signal_kwargs=signal_kwargs, **write_concern) def delete(self, parent_level=None, **write_concern): self.is_deleted = True self.deleted_at = datetime.now() level = self.DELETING_LEVEL if parent_level is None else parent_level if level is not None: self.deleting_level = level for child in self.DELETING_CHILDS: model_ = get_class(child) query = {self.delete_by(): self, "is_deleted": {"$ne": True}} model_.objects(**query).delete(parent_level=level) return self.save() def restore(self, parent_level=None): self.is_deleted = False del self.deleted_at del self.deleting_level level = self.DELETING_LEVEL if parent_level is None else parent_level if level is not None: for child in self.DELETING_CHILDS: model_ = get_class(child) query = {self.delete_by(): self, "deleting_level": level} model_.objects(**query).restore(parent_level=level) return self.save() @classmethod def to_ref_cls(cls, pk): return DBRef(cls._get_collection_name(), pk) @classmethod def dynamic_field_ref(cls, pk): return {'_ref': cls.to_ref_cls(pk), '_cls': cls.__name__} @classmethod def delete_by(cls): return snake_case(cls.__name__) @classmethod def from_son(cls, data, created=False): return cls._from_son(data, created=created) @property def serializer(self): if self._serializer is None: names = self.__class__.__module__.split('.') names.pop() names.append("serializer") mod = __import__(".".join(names), fromlist=self.default_serializer) self._serializer = getattr(mod, self.default_serializer) return self._serializer """