class Device(Document): serialNumberInserv = fields.StringField() system = fields.EmbeddedDocumentField(System) capacity = fields.EmbeddedDocumentField(Capacity) performance = fields.EmbeddedDocumentField(Performance) disks = fields.EmbeddedDocumentField(Disks) nodes = fields.DictField() authorized = fields.EmbeddedDocumentField(Authorized) updated = fields.DateTimeField() date = fields.DateTimeField() def __str__(self): if self.system and self.system.fullModel: return "{} ({})".format(self.system.fullModel, self.serialNumberInserv) return "{}".format(self.serialNumberInserv) @staticmethod def for_user(user_id): tenant = Tenant.id_for_user(user_id) d = Device.objects.filter(authorized__tenants=tenant) d._user_id = user_id return d def has_triggered(self): user_ids = Tenant.objects.filter( tenant_id__in=self.authorized.tenants).values_list('user_id') statuses = Status.objects.filter(device_id=str(self.id), user_id__in=user_ids) for s in statuses: if s.current_check(): return True return False
class Post(Document): created_at = fields.DateTimeField( default=datetime.datetime.now, required=True, editable=False, ) title = fields.StringField(max_length=255, required=True) slug = fields.StringField(max_length=255, required=True, primary_key=True) comments = fields.ListField(fields.EmbeddedDocumentField('Comment')) def get_absolute_url(self): return reverse('post', kwargs={"slug": self.slug}) def __unicode__(self): return self.title @property def post_type(self): return self.__class__.__name__ meta = { 'indexes': ['-created_at', 'slug'], 'ordering': ['-created_at'], 'allow_inheritance': True }
class Status(Document): user_id = fields.IntField() criteria = fields.EmbeddedDocumentField(StatusCriteria) device_id = fields.StringField() active = fields.BooleanField() @property def device(self): return Device.objects.get(id=self.device_id) def current_value(self): return self.criteria.metric_value_for(self.device) def current_check(self): return self.criteria.operation_check(self.current_value()) def __str__(self): return "{}{}".format(self.device_id, self.criteria) @staticmethod def only_triggered_for(user_id): active = Status.objects.filter(user_id=user_id, active=True) triggered_ids = [] for obj in active: if obj.current_check(): triggered_ids.append(str(obj.id)) return Status.objects.filter(id__in=triggered_ids) @staticmethod def for_user(user_id): return Status.objects.filter(user_id=user_id)
class DataSource(EmbeddedDocument): """Data Source class """ name = fields.StringField(blank=False) url_query = fields.StringField(blank=False) query_options = fields.DictField(blank=True) authentication = fields.EmbeddedDocumentField(Authentication)
class Notifications(EmbeddedDocument): user_id = fields.StringField(unique=False) notification_id = fields.StringField(unique=False) notification_received_at = fields.DateTimeField(default=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), unique=False) notification_type = fields.IntField() notification_details = fields.EmbeddedDocumentField(NotificationDetails, required=False, default= None, blank=True,unique=False)
class Setup(Document): user = fields.StringField(max_length=50) service = fields.StringField(max_length=50) cloud = fields.StringField(max_length=50) options = fields.EmbeddedDocumentField(Options, blank=True) playbook = fields.ReferenceField(AnsiblePlaybook, blank=True) key_id = fields.ReferenceField(Key, blank=True) status = fields.StringField()
class Result(Document): """Result class """ title = fields.StringField(blank=False) xml_content = fields.StringField(blank=False) template_info = fields.EmbeddedDocumentField(TemplateInfo) detail_url = fields.StringField(blank=True) access_data_url = fields.StringField(blank=True)
class DataSource(EmbeddedDocument): """Data Source class""" name = fields.StringField(blank=False) url_query = fields.StringField(blank=False) query_options = fields.DictField(blank=True) authentication = fields.EmbeddedDocumentField(Authentication) order_by_field = fields.StringField(blank=True, default="") capabilities = fields.DictField(blank=True)
class Result(Document): """Result class""" title = fields.StringField(blank=False) xml_content = fields.StringField(blank=False) template_info = fields.EmbeddedDocumentField(TemplateInfo) permission_url = fields.StringField(blank=True, null=True) detail_url = fields.StringField(blank=True) access_data_url = fields.StringField(blank=True) last_modification_date = fields.DateTimeField(blank=True, default=None)
class DataItem(Document): """ Data Item object """ # When data is deleted, all relative data item is deleted as well data = fields.ReferenceField(Data, blank=False, reverse_delete_rule=CASCADE) template = fields.ReferenceField(Template, blank=False) list_content = fields.ListField(fields.EmbeddedDocumentField(Item), default=[], blank=False) last_modification_date = fields.DateTimeField(blank=True, default=None) @staticmethod def get_by_data(data): """ Return a Data Item with the data given. Args: data: Returns: """ try: return DataItem.objects(data=data).get() except mongoengine_errors.DoesNotExist as e: raise exceptions.DoesNotExist(e.message) except Exception as ex: raise exceptions.ModelError(ex.message) @staticmethod def delete_from_data(data): """ Delete data items relative to the given data Args: data: Returns: """ DataItem.objects(data=data).delete() @staticmethod def execute_query_distinct_by_data(query): """Execute a query on the DataItem collection distinct by data. Args: query: Returns: """ return DataItem.objects(__raw__=query).distinct("data")
class AbstractQuery(Document): """Abstract Query""" user_id = fields.StringField(blank=False) content = fields.StringField(blank=True) templates = fields.ListField( fields.ReferenceField(Template, blank=True), blank=True, default=[] ) data_sources = fields.ListField( fields.EmbeddedDocumentField(DataSource, blank=True), blank=True, default=[] ) meta = { "abstract": True, }
class Post(Document): created_at = fields.DateTimeField(default=datetime.datetime.now, editable=False) title = fields.StringField(max_length=255) slug = fields.StringField(max_length=255, primary_key=True) comments = fields.ListField(fields.EmbeddedDocumentField("Comment"), default=[], blank=True) def get_absolute_url(self): return reverse("post", kwargs={"slug": self.slug}) def __unicode__(self): return self.title @property def post_type(self): return self.__class__.__name__ meta = { "indexes": ["-created_at", "slug"], "ordering": ["-created_at"], "allow_inheritance": True, }
class Performance(EmbeddedDocument): portBandwidthData = fields.EmbeddedDocumentField(PerformanceBandwidth, blank=True) summary = fields.EmbeddedDocumentField(PerformanceSummary)
class DefaultStatus(Document): criteria = fields.EmbeddedDocumentField(StatusCriteria) name = fields.StringField()
class AnsiblePlaybook(Document): plays = fields.ListField( fields.EmbeddedDocumentField(AnsiblePlay, blank=True)) stats = fields.DictField() created_at = fields.DateTimeField(default=datetime.now)
class AnsiblePlay(EmbeddedDocument): play = fields.DictField() tasks = fields.ListField( fields.EmbeddedDocumentField(AnsibleTask, blank=True))
class Disks(EmbeddedDocument): total = fields.DictField() byType = fields.EmbeddedDocumentField(DisksByType) state = fields.StringField()
class User(document.Document): SEXO_HOMBRE = 'masculino' SEXO_MUJER = 'femenino' SEXOS = ((None, 'No definido'), (SEXO_HOMBRE, 'Masculino'), (SEXO_MUJER, 'Femenino')) """A User document that aims to mirror most of the API specified by Django at http://docs.djangoproject.com/en/dev/topics/auth/#users """ username = fields.StringField( max_length=250, verbose_name=('username'), help_text= ("Required. 250 characters or fewer. Letters, numbers and @/./+/-/_ characters" ), required=False) first_name = fields.StringField( max_length=250, blank=True, verbose_name=('first name'), ) last_name = fields.StringField(max_length=250, blank=True, verbose_name=('last name')) email = fields.EmailField(verbose_name=('e-mail address'), blank=False) password = fields.StringField( blank=True, max_length=128, verbose_name=('password'), help_text= ("Use '[algo]$[iterations]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>." )) is_staff = fields.BooleanField( default=False, verbose_name=('staff status'), help_text=( "Designates whether the user can log into this admin site.")) is_active = fields.BooleanField( default=True, verbose_name=('active'), help_text= ("Designates whether this user should be treated as active. Unselect this instead of deleting accounts." )) is_superuser = fields.BooleanField( default=False, verbose_name=('superuser status'), help_text= ("Designates that this user has all permissions without explicitly assigning them." )) last_login = fields.DateTimeField(default=timezone.now, verbose_name=('last login')) date_joined = fields.DateTimeField(default=timezone.now, verbose_name=('date joined')) user_permissions = fields.ListField( fields.ReferenceField(Permission), verbose_name=('user permissions'), blank=True, help_text=('Permissions for the user.')) birthdate = DateField(blank=True) # image = LocalStorageFileField(upload_to='users/') web_url = fields.URLField(blank=True) facebook_page = fields.URLField(blank=True) youtube_channel = fields.URLField(blank=True) genere = fields.StringField(choices=SEXOS, required=False, blank=True) is_complete = fields.BooleanField(default=False) providers = fields.ListField(fields.EmbeddedDocumentField('Provider'), blank=True) photo_url = fields.URLField(blank=True) uid = fields.StringField(blank=False, required=True) display_name = fields.StringField(blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] meta = { 'allow_inheritance': True, 'indexes': [{ 'fields': ['username'], 'unique': True, 'sparse': True }] } def __unicode__(self): return self.username def get_full_name(self): """Returns the users first and last names, separated by a space. """ full_name = u'%s %s' % (self.first_name or '', self.last_name or '') return full_name.strip() def is_anonymous(self): return False def is_authenticated(self): return True def set_password(self, raw_password): """Sets the user's password - always use this rather than directly assigning to :attr:`~mongoengine.django.auth.User.password` as the password is hashed before storage. """ self.password = make_password(raw_password) self.save() return self def check_password(self, raw_password): """Checks the user's password against a provided password - always use this rather than directly comparing to :attr:`~mongoengine.django.auth.User.password` as the password is hashed before storage. """ return check_password(raw_password, self.password) @classmethod def create_user(cls, username, password, email=None): """Create (and save) a new user with the given username, password and email address. """ now = timezone.now() # Normalize the address by lowercasing the domain part of the email # address. if email is not None: try: email_name, domain_part = email.strip().split('@', 1) except ValueError: pass else: email = '@'.join([email_name, domain_part.lower()]) user = cls(username=username, email=email, date_joined=now) user.set_password(password) user.save() return user def get_group_permissions(self, obj=None): """ Returns a list of permission strings that this user has through his/her groups. This method queries all available auth backends. If an object is passed in, only permissions matching this object are returned. """ permissions = set() for backend in auth.get_backends(): if hasattr(backend, "get_group_permissions"): permissions.update(backend.get_group_permissions(self, obj)) return permissions def get_all_permissions(self, obj=None): return _user_get_all_permissions(self, obj) def has_perm(self, perm, obj=None): """ Returns True if the user has the specified permission. This method queries all available auth backends, but returns immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provided, permissions for this specific object are checked. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return True # Otherwise we need to check the backends. return _user_has_perm(self, perm, obj) def has_module_perms(self, app_label): """ Returns True if the user has any permissions in the given app label. Uses pretty much the same logic as has_perm, above. """ # Active superusers have all permissions. if self.is_active and self.is_superuser: return True return _user_has_module_perms(self, app_label) def email_user(self, subject, message, from_email=None): "Sends an e-mail to this User." from django.core.mail import send_mail send_mail(subject, message, from_email, [self.email])