def dashboard_view(request): ctx = dict() ctx['streams_status_counts'] = ModelManager.handle( 'streams.Stream', 'all').values('status').annotate(total=Count('status')) ctx['functions_status_counts'] = ModelManager.handle( 'streams.FunctionInstance', 'all').values('status').annotate(total=Count('status')) return render(request, template_name='streams/dashboard.html', context=ctx, )
def _query_serialized_function_variables(function_instance, iot): variables = ModelManager.handle( 'streams.variable', 'filter', function_instance=function_instance, iot=iot) return [var_.to_entity.as_dict for var_ in variables]
def test_create_output(self): fi = ModelManager.handle('streams.functioninstance', 'all')[0] output = Variable.create('text', 'output_1', 'My name is Foo and I love Bars') var_orm, _ = VariableModel.create_output(fi.uuid, output) assert var_orm.iot == 'output' assert var_orm.to_entity assert var_orm.rank == 0
def create(self, validated_data): workspace = ModelManager.handle( 'accounts.workspace', 'create', name=validated_data['name'], business=validated_data['business'], ) return workspace
def validate_stream(self, stream_uuid): try: stream = ModelManager.handle('streams.stream', 'get', uuid=stream_uuid) except ObjectDoesNotExist: raise uuid_validation_error(stream_uuid) return stream
def validate_business(self, business_uuid): try: business = ModelManager.handle('accounts.business', 'get', uuid=business_uuid) except ObjectDoesNotExist: raise serializers.ValidationError( "Business is invalid: '%s' doesn't exist." % business_uuid) return business
def validate_type(self, ft_uuid): try: func_type = ModelManager.handle('streams.functiontype', 'get', uuid=ft_uuid) except ObjectDoesNotExist: raise uuid_validation_error(ft_uuid) return func_type
def validate(self, attrs): organization_slug = attrs.get('organization_slug') if not organization_slug: organization_slug = slugify(attrs['organization_name']) validator = MaxLengthValidator(limit_value=150) validator(organization_slug) attrs['organization_slug'] = organization_slug try: ModelManager.handle( 'accounts.business', 'get', organization_slug=organization_slug, ) raise serializers.ValidationError( "Invalid organization slug '%s': already exists." % organization_slug) except ObjectDoesNotExist: return attrs
def list(self, request): filters = {} initial_queryset = None for key, value in request.query_params.items(): self.check_filter(key) if key not in ['limit', 'offset']: if key in ['is_staff', 'is_active']: filters[key] = True if value == 'true' else False elif key == 'related_to_workspace': workspace_uuid = request.query_params.get( 'related_to_workspace') try: workspace = ModelManager.handle( 'accounts.workspace', 'get', uuid=workspace_uuid) except ObjectDoesNotExist: raise ParseError( "Workspace '%s' doesn't exist." % workspace_uuid) initial_queryset = workspace.accountmodel_set.all() if initial_queryset: accounts = initial_queryset.filter(**filters) else: accounts = ModelManager.handle( 'accounts.account', 'filter', **filters, ) items, metadata = self.filter_paginated_results(request, accounts) list_serializer = AccountListSerializer( items, many=True, request=request) response_data = { 'total_queryset': len(accounts), 'count': len(items), 'data': list_serializer.data, 'metadata': { **metadata, **{'valid_filters': self.VALID_FILTERS} } } return Response(response_data, status=HTTP_200_OK)
def create(self, validated_data): stream = ModelManager.handle( 'streams.stream', 'create', name=validated_data['name'], account=validated_data['account'], workspace=validated_data['workspace'], ) return stream
def create(self, validated_data): function_instance = ModelManager.handle( 'streams.functioninstance', 'create', function_type=validated_data['type'], stream=validated_data['stream'], position=validated_data['position'], ) return function_instance
def validate_name(self, name): query = ModelManager.handle( 'accounts.workspace', 'filter', name=name, business__uuid=self.initial_data.get('business')) if len(query) > 0: raise serializers.ValidationError( "A workspace with that name '%s' already exists " "at the scope of the business." % name) return name
def validate(self, attrs): """ It returns the corresponding UserModel instance. The unique validation is check that an account exists. Any additional validation logic for login is not performed in the serializer scope. """ if self.initial_data['auth_type'] == 'email': id_field = 'email' else: id_field = 'auth_id' id_value = attrs['identifier'] try: ModelManager.handle('accounts.account', 'get', **{id_field: id_value}) return attrs except ObjectDoesNotExist: raise serializers.ValidationError( "There isn't an account with the identifier provided: '%s'" % id_value)
def retrieve(self, request, uuid=None): try: resource = ModelManager.handle( self.app_model_name, 'get', uuid=uuid) except ObjectDoesNotExist: raise NotFound( detail=f"resource identifier: '{uuid}' doesn't exist.") serializer = self.RetrieveSerializer(resource) return Response( serializer.data, status=HTTP_200_OK)
def create(self, validated_data): account_creation_data = self.get_account_creation_data(validated_data) account = ModelManager.handle( 'accounts.account', 'create_account', **account_creation_data, ) account.groups.add(1) # business_administrator business_creation_data = { 'master_account': account, 'organization_name': validated_data['organization_name'], 'organization_slug': validated_data['organization_slug'], } business = ModelManager.handle( 'accounts.business', 'create', **business_creation_data, ) return business
def test_accounts_models_relationships(): users = ModelManager.handle('accounts.user', 'all') for user in users: user_ws = user.account.workspaces.all() assert len(user_ws) == 1 ws = user_ws[0] accounts = ws.accounts.all() business_account = (accounts[1] if accounts[0].uuid == user.account.uuid else accounts[0]) assert len(accounts) == 2 assert ws.name == '%s-%s' % (user.account.username, 'default') assert business_account == user.business.master_account
def post(self, request): serializer = CreateFILogMessageSerializer(data=request.data) serializer.is_valid(raise_exception=True) fi_log_message = ModelManager.handle( 'streams.FunctionInstanceLogMessage', 'create', function_instance=request.fi, log_message=serializer.validated_data['log_message'], log_level=serializer.validated_data['log_level'], ) # TODO: Send changes trough a socket to application client return Response(status=HTTP_200_OK)
def apply_list_filters(self, request) -> Tuple: filters = self.build_filters(request) try: queryset = ModelManager.handle( self.app_model_name, 'filter', **filters, ) items, metadata = self.filter_paginated_results(request, queryset) except: self.raise_invalid_filters_error() metadata = dict(**metadata, **{'valid_filters': self.VALID_FILTERS}) return len(queryset), items, metadata
def create(self, validated_data): account_creation_data = self.get_account_creation_data(validated_data) account = ModelManager.handle( 'accounts.account', 'create_account', **account_creation_data, ) account.groups.add(2) # developer user_creation_data = { 'account': account, 'business': validated_data['business'], 'first_name': validated_data['first_name'], 'last_name': validated_data['last_name'], } user = ModelManager.handle( 'accounts.user', 'create', **user_creation_data, ) return user
def create(self, validated_data): account = validated_data['account'] function_type = ModelManager.handle( 'streams.functiontype', 'create', key=validated_data['key'], verbose_name=validated_data['verbose_name'], description=validated_data['description'], inputs=validated_data['inputs'], outputs=validated_data['outputs'], account=account, ) return function_type
def create(self, validated_data): variable = ModelManager.handle( 'streams.variable', 'create', iot=validated_data['iot'], id_name=validated_data['id_name'], type=validated_data['type'], charset=validated_data['charset'], bytes=validated_data['bytes'], function_instance=validated_data['function_instance'], rank=validated_data['rank'], ) return variable
def destroy(self, request, uuid=None): try: st = ModelManager.handle( 'streams.stream', 'get', uuid=uuid, ) except ObjectDoesNotExist: raise NotFound( detail=f"resource identifier: '{uuid}' doesn't exist.") st.cancel() serializer = StreamSerializer(st) return Response(serializer.data, status=HTTP_200_OK)
def validate(self, attrs): organization_slug = attrs['organization_slug'] try: business = ModelManager.handle( 'accounts.business', 'get', organization_slug=organization_slug, ) attrs['business'] = business except ObjectDoesNotExist: raise serializers.ValidationError( "Invalid organization slug '%s': doesn't exist." % organization_slug) return attrs
def test_streams_models_relationships(): streams = ModelManager.handle('streams.stream', 'all') st = streams[0] functions = st.functions.all() assert len(functions) > 0 fi = functions[0] ft = fi.function_type instances = ft.instances.all() inst = instances[0] assert fi == inst vars = fi.variables.all() assert len(vars) > 0
def handle(self, *args, **options): model_name = '{0}{1}'.format( options['model_name'].lower(), 'model' if 'model' not in options['model_name'].lower() else '') json_data = options['json_data'] try: object_data = json.loads(json_data) except json.JSONDecodeError: raise CommandError( '%s json_data cannot be correctly deserialized' % json_data) try: item = ModelManager.handle(f'accounts.{model_name}', 'create', **object_data) except Exception as err: raise CommandError( 'An error occurred while creating the Workspace: %s' % err) self.stdout.write( self.style.SUCCESS('Successfully created "%s" uuid="%s"' % (model_name, item.uuid)))
def partial_update(self, request, uuid=None): if 'body' not in request.data.keys(): raise ParseError(detail={'body': 'field is required.'}) else: body = request.data['body'] if not body: raise ParseError(detail={'body': 'field cannot be null.'}) validate_b64_encoded(body) try: variable = ModelManager.handle( 'streams.variable', 'get', uuid=uuid, ) except ObjectDoesNotExist: raise NotFound( detail=f"resource identifier: '{uuid}' doesn't exist.") variable.body = decode_b64str(body) variable.save() serializer = VariableSerializer(variable) return Response(serializer.data, status=HTTP_200_OK)
def test_to_entity(self): users = ModelManager.handle('accounts.user', 'all') for user in users: assert isinstance(user.to_entity, UserEntity)
def test_to_entity(self): accounts = ModelManager.handle('accounts.account', 'all') for account in accounts: assert isinstance(account.to_entity, AccountEntity)
def test_to_entity(self): businesses = ModelManager.handle('accounts.business', 'all') for bs in businesses: assert isinstance(bs.to_entity, BusinessEntity)
def validate_email(self, email): try: ModelManager.handle('accounts.account', 'get', email=email) raise serializers.ValidationError("'%s' already exist." % email) except ObjectDoesNotExist: return email