class XSerializer(serializers.Serializer): x = serializers.UUIDField()
class ProviderSerializer(serializers.ModelSerializer): """Serializer for the Provider model.""" uuid = serializers.UUIDField(read_only=True) name = serializers.CharField(max_length=256, required=True, allow_null=False, allow_blank=False) type = serializers.ChoiceField(choices=Provider.PROVIDER_CHOICES) created_timestamp = serializers.DateTimeField(read_only=True) authentication = ProviderAuthenticationSerializer() billing_source = ProviderBillingSourceSerializer(default={'bucket': ''}) customer = CustomerSerializer(read_only=True) created_by = UserSerializer(read_only=True) # pylint: disable=too-few-public-methods class Meta: """Metadata for the serializer.""" model = Provider fields = ('uuid', 'name', 'type', 'authentication', 'billing_source', 'customer', 'created_by', 'created_timestamp') @transaction.atomic def create(self, validated_data): """Create a provider from validated data.""" user = None customer = None request = self.context.get('request') if request and hasattr(request, 'user'): user = request.user if user.customer: customer = user.customer else: key = 'customer' message = 'Customer for requesting user could not be found.' raise serializers.ValidationError(error_obj(key, message)) else: key = 'created_by' message = 'Requesting user could not be found.' raise serializers.ValidationError(error_obj(key, message)) if 'billing_source' in validated_data: billing_source = validated_data.pop('billing_source') bucket = billing_source.get('bucket') data_source = billing_source.get('data_source', {}) else: # Because of a unique together constraint, this is done # to allow for this field to be non-required for OCP # but will still have a blank no-op entry in the DB billing_source = {'bucket': ''} data_source = None authentication = validated_data.pop('authentication') provider_resource_name = authentication.get('provider_resource_name') credentials = authentication.get('credentials') provider_type = validated_data['type'] interface = ProviderAccessor(provider_type) if credentials and data_source: interface.cost_usage_source_ready(credentials, data_source) else: interface.cost_usage_source_ready(provider_resource_name, bucket) bill, __ = ProviderBillingSource.objects.get_or_create( **billing_source) auth, __ = ProviderAuthentication.objects.get_or_create( **authentication) # We can re-use a billing source or a auth, but not the same combination. unique_count = Provider.objects.filter(authentication=auth)\ .filter(billing_source=bill).count() if unique_count != 0: error = { 'Error': 'A Provider already exists with that Authentication and Billing Source' } raise serializers.ValidationError(error) provider = Provider.objects.create(**validated_data) provider.customer = customer provider.created_by = user provider.authentication = auth provider.billing_source = bill provider.save() return provider
class GoodsFlagSerializer(serializers.Serializer): id = serializers.UUIDField() name = serializers.CharField()
class ApplySerializer(serializers.Serializer): apply_permission_name = serializers.CharField( max_length=128, default=DefaultPermissionName(), label=_('Apply name')) apply_nodes = serializers.ListField(required=False, allow_null=True, child=serializers.UUIDField(), label=_('Apply nodes'), help_text=asset_or_node_help_text, default=list) apply_nodes_display = serializers.ListField(child=serializers.CharField(), label=_('Apply nodes display'), required=False) # 申请信息 apply_assets = serializers.ListField(required=False, allow_null=True, child=serializers.UUIDField(), label=_('Apply assets'), help_text=asset_or_node_help_text) apply_assets_display = serializers.ListField( required=False, read_only=True, child=serializers.CharField(), label=_('Apply assets display'), allow_null=True, default=list) apply_system_users = serializers.ListField(required=True, allow_null=True, child=serializers.UUIDField(), label=_('Apply system users')) apply_system_users_display = serializers.ListField( required=False, read_only=True, child=serializers.CharField(), label=_('Apply assets display'), allow_null=True, default=list, ) apply_actions = ActionsField(required=True, allow_null=True) apply_actions_display = serializers.ListField( required=False, read_only=True, child=serializers.CharField(), label=_('Apply assets display'), allow_null=True, default=list, ) apply_date_start = serializers.DateTimeField( required=True, label=_('Date start'), allow_null=True, ) apply_date_expired = serializers.DateTimeField( required=True, label=_('Date expired'), allow_null=True, ) def validate_approve_permission_name(self, permission_name): if not isinstance(self.root.instance, Ticket): return permission_name with tmp_to_org(self.root.instance.org_id): already_exists = AssetPermission.objects.filter( name=permission_name).exists() if not already_exists: return permission_name raise serializers.ValidationError( _('Permission named `{}` already exists'.format(permission_name))) def validate(self, attrs): if not attrs.get('apply_nodes') and not attrs.get('apply_assets'): raise serializers.ValidationError({ 'apply_nodes': asset_or_node_help_text, 'apply_assets': asset_or_node_help_text, }) apply_date_start = attrs['apply_date_start'].strftime( '%Y-%m-%d %H:%M:%S') apply_date_expired = attrs['apply_date_expired'].strftime( '%Y-%m-%d %H:%M:%S') if apply_date_expired <= apply_date_start: error = _( 'The expiration date should be greater than the start date') raise serializers.ValidationError({'apply_date_expired': error}) attrs['apply_date_start'] = apply_date_start attrs['apply_date_expired'] = apply_date_expired return attrs
class PassageDetailSerializer(serializers.ModelSerializer): id = serializers.UUIDField( validators=[], source='passage_id' ) # Disable the validators for the id, which improves performance (rps) by over 200% class Meta: model = Passage # exclude passage_id. We map id (on the serializer) to passage_id (on the model) # therefore we are practically excluding the Passage.id field exclude = ['passage_id'] validators = [ # Disable UniqueTogetherValidator for (passage_id, volgnummer) # for performance ] def create(self, validated_data): try: return super().create(validated_data) except IntegrityError as e: # this is pretty nasty to check the string like this, however when # a partition does not exist an IntegrityError is raised - in this # case we don't want to return a 409 duplicate error. Unfortunately # the string argument is the only way to distinguish between # different types of IntegrityError. if 'duplicate key' in e.args[0]: log.info( f"DuplicateIdError for passage_id {validated_data['passage_id']}, volgnummer {validated_data.get('volgnummer', '*missing*')}" ) raise DuplicateIdError(str(e)) else: raise def validate_datum_eerste_toelating(self, value): if value is None: return None return date(year=value.year, month=1, day=1) def validate_datum_tenaamstelling(self, value): return None def validate_toegestane_maximum_massa_voertuig(self, value): if value is not None and value <= 3500: return 1500 return value def validate(self, data): self._validate_voertuigcategorie(data) self._validate_inrichting(data) return data def _validate_inrichting(self, data): if 'voertuig_soort' in data: if data['voertuig_soort'].lower() == 'personenauto': data['inrichting'] = 'Personenauto' def _validate_voertuigcategorie(self, data): if 'toegestane_maximum_massa_voertuig' in data: if data['toegestane_maximum_massa_voertuig'] <= 3500: data['europese_voertuigcategorie_toevoeging'] = None data['merk'] = None
class WorkflowSerializer(CreateWithParentModelSerializer): id = serializers.UUIDField(format='hex', required=False) inputs = WorkflowInputSerializer(many=True, required=False, allow_null=True) fixed_inputs = FixedWorkflowInputSerializer(many=True, required=False, allow_null=True) outputs = WorkflowOutputSerializer(many=True) steps = AbstractWorkflowSerializer(many=True) workflow_import = WorkflowImportSerializer(allow_null=True, required=False) class Meta: model = Workflow fields = ('id', 'name', 'steps', 'inputs', 'fixed_inputs', 'outputs', 'datetime_created', 'workflow_import') def create(self, validated_data): data = copy.deepcopy(validated_data) # Can't create inputs or outputs until workflow exists inputs = self.initial_data.get('inputs', None) fixed_inputs = self.initial_data.get('fixed_inputs', None) outputs = self.initial_data.get('outputs', None) steps = self.initial_data.get('steps', None) workflow_import = self.initial_data.get('workflow_import', None) data.pop('inputs', None) data.pop('fixed_inputs', None) data.pop('outputs', None) data.pop('steps', None) data.pop('workflow_import', None) workflow = super(WorkflowSerializer, self).create(data) for step_data in steps: s = AbstractWorkflowSerializer(data=step_data, context={ 'parent_field': 'parent_workflow', 'parent_instance': workflow }) s.is_valid(raise_exception=True) s.save() if inputs is not None: for input_data in inputs: s = WorkflowInputSerializer(data=input_data, context={ 'parent_field': 'workflow', 'parent_instance': workflow }) s.is_valid(raise_exception=True) s.save() if fixed_inputs is not None: for fixed_input_data in fixed_inputs: s = FixedWorkflowInputSerializer(data=fixed_input_data, context={ 'parent_field': 'workflow', 'parent_instance': workflow }) s.is_valid(raise_exception=True) s.save() for output_data in outputs: s = WorkflowOutputSerializer(data=output_data, context={ 'parent_field': 'workflow', 'parent_instance': workflow }) s.is_valid(raise_exception=True) s.save() if workflow_import is not None: s = WorkflowImportSerializer(data=workflow_import, context={ 'parent_field': 'workflow', 'parent_instance': workflow }) s.is_valid(raise_exception=True) s.save() workflow.post_create() return workflow
class MemberAddSerializer(serializers.ModelSerializer): """This Serializer is used when we are adding a Member. """ url = serializers.SerializerMethodField() email = serializers.EmailField(required=False, ) uuid = serializers.UUIDField(read_only=True) user = serializers.UUIDField( required=False) # to be added later when we willa dd shadow user type = serializers.ChoiceField(required=True, choices=config.MEMBER_TYPES) class Meta: model = models.Member exclude = ('id', ) validators = [ UniqueTogetherValidator(queryset=models.Member.objects.all(), fields=( 'email', 'organization', )) ] def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(MemberAddSerializer, self).__init__(*args, **kwargs) def get_url(self, obj): """ :param obj: :return: """ from django.urls import reverse # import ipdb;ipdb.set_trace() url_name = '{app_namespace}:member-urls:members-detail'.format( app_namespace=getattr(settings, 'APP_NAMESPACE')) owner = self.request.parser_context.get('kwargs').get('owner') organization = self.request.parser_context.get('kwargs').get( 'organization') return self.request.build_absolute_uri( reverse(url_name, args=(owner, organization, obj.uuid))) def _get_user_api(self): """ """ if config.USER_SERVER_URL.endswith( '/') and config.USER_CREATE_API.startswith('/'): return '{0}{1}'.format(config.USER_SERVER_URL[:-1], config.USER_CREATE_API) elif not config.USER_SERVER_URL.endswith( '/') and not config.USER_CREATE_API.startswith('/'): return '{0}/{1}'.format(config.USER_SERVER_URL, config.USER_CREATE_API) return '{0}{1}'.format(config.USER_SERVER_URL, config.USER_CREATE_API) def _get_default_image(self): """ """ return config.DEFAULT_IMAGE_PATH def _get_or_create_shadow_user(self, email): """ - Here we manage creation of Shadow User in Authentication Server. - First we will check wether user with same email if not only then we will create shadow user. """ url = self._get_user_api() # image = open(self._get_default_image(), 'rb') data = {'email': email, 'is_active': False} # ToDo : Not checking for any error in below API # return requests.post(url, files={'avatar': image}, data=data).json() return requests.post(url, data=data).json() def create(self, validated_data): """ :param validated_data: Validated data. """ # check User Server Url has been set mentioned or not if config.USER_SERVER_URL is None: raise NotAcceptable( 'you have not mentioned User Server Url in settings.') # create shadow user and save user token in Member instance email = validated_data.get('email') user = self._get_or_create_shadow_user(email) validated_data.update({'user': user.get('uuid')}) return super(MemberAddSerializer, self).create(validated_data)
class PutReserveBooksSerializer(serializers.Serializer): client_reserve = serializers.UUIDField() date_loan = serializers.DateField() date_devolution = serializers.DateField()
class ImageDetailInputErrorSerializer(serializers.Serializer): identifier = serializers.UUIDField()
class PriceSerializer(serializers.Serializer): id = serializers.UUIDField() price = serializers.FloatField()
class NftToItemSerializer(serializers.Serializer): id = serializers.UUIDField()
class UpdateStyleImageSerializer(serializers.Serializer): id = serializers.UUIDField() update_name = serializers.CharField(max_length=100)
class ConnectionsAcceptConnectionSerializer(serializers.ModelSerializer): uuid = serializers.UUIDField(allow_null=False) class Meta: model = User fields = ['uuid']
class MouseClickSerializer(serializers.ModelSerializer): user_id = serializers.UUIDField() class Meta: model = models.PageLoad fields = ('user_id', 'session', 'created_at')
class DiceSequenceListByUUIDSerializer(serializers.ModelSerializer): uuid_list = serializers.ListField(child=serializers.UUIDField()) class Meta: model = DiceSequence fields = ('uuid_list', )
class CollectionVersionSerializer(SingleArtifactContentSerializer, ContentChecksumSerializer): """ A serializer for CollectionVersion Content. """ id = serializers.UUIDField(source="pk", help_text="A collection identifier.") authors = serializers.ListField( help_text=_("A list of the CollectionVersion content's authors."), child=serializers.CharField(max_length=64), ) contents = serializers.ListField( child=serializers.DictField(), help_text=_("A JSON field with data about the contents.")) dependencies = serializers.DictField(help_text=_( "A dict declaring Collections that this collection requires to be installed for it to " "be usable.")) description = serializers.CharField( help_text=_("A short summary description of the collection."), allow_blank=True) docs_blob = serializers.DictField(help_text=_( "A JSON field holding the various documentation blobs in the collection." )) documentation = serializers.URLField( help_text=_("The URL to any online docs."), allow_blank=True, max_length=2000) homepage = serializers.URLField( help_text=_("The URL to the homepage of the collection/project."), allow_blank=True, max_length=2000, ) issues = serializers.URLField( help_text=_("The URL to the collection issue tracker."), allow_blank=True, max_length=2000) certification = serializers.CharField( help_text=_("Indicates that the version is certified")) license = serializers.ListField( help_text=_("A list of licenses for content inside of a collection."), child=serializers.CharField(max_length=32), ) name = serializers.CharField(help_text=_("The name of the collection."), max_length=32) namespace = serializers.CharField( help_text=_("The namespace of the collection."), max_length=32) repository = serializers.URLField( help_text=_("The URL of the originating SCM repository."), allow_blank=True, max_length=2000) tags = TagNestedSerializer(many=True, read_only=True) version = serializers.CharField( help_text=_("The version of the collection."), max_length=32) deprecated = serializers.BooleanField( source="collection.deprecated", help_text=_("Whether or not the collection has been deprecated."), read_only=True, ) class Meta: fields = (tuple( set(SingleArtifactContentSerializer.Meta.fields) - {"relative_path"}) + ContentChecksumSerializer.Meta.fields + ( "id", "authors", "contents", "dependencies", "description", "docs_blob", "documentation", "homepage", "issues", "certification", "license", "name", "namespace", "repository", "tags", "version", "deprecated", )) model = CollectionVersion
class TaskSerializer(serializers.Serializer): id = serializers.UUIDField(source='uuid', read_only=True) uuid = serializers.UUIDField(read_only=True) short_id = serializers.IntegerField(source='id', read_only=True) status = serializers.CharField(required=False) urgency = serializers.FloatField(read_only=True) description = serializers.CharField(required=True) priority = serializers.CharField(required=False, allow_blank=True) project = serializers.CharField(required=False, allow_blank=True) due = serializers.DateTimeField(required=False) entry = serializers.DateTimeField(read_only=True) modified = serializers.DateTimeField(read_only=True) start = serializers.DateTimeField(required=False) wait = serializers.DateTimeField(required=False) until = serializers.DateTimeField(required=False) scheduled = serializers.DateTimeField(required=False) depends = serializers.ListField( child=serializers.UUIDField(), required=False, ) blocks = serializers.SerializerMethodField() annotations = serializers.ListField( child=serializers.CharField(), required=False, ) tags = serializers.ListField(child=serializers.CharField(), required=False) imask = serializers.CharField(read_only=True) udas = serializers.SerializerMethodField() def __init__(self, *args, **kwargs): self._store = kwargs.pop('store') super(TaskSerializer, self).__init__(*args, **kwargs) @property def store(self): return self._store def get_udas(self, obj): udas = {} for field in self.store.client.config.get_udas().keys(): if field in obj: udas[field] = obj[field] return udas def get_blocks(self, obj): return self.store.get_blocks_for_task(obj) def update(self, store, pk, data): original = store.client.get_task(uuid=pk)[1] for k, v in data.items(): if k == 'priority' and v == '': v = None original[k] = v changes = original.get_changes(keep=True) store.client.task_update(original) return original, changes def create(self, store, data): for k, v in data.items(): if not v: data.pop(k, None) return store.client.task_add(**data)
class UUIDModelSerializerMixin(ModelSerializer): id = serializers.UUIDField(default=uuid.uuid4, read_only=True)
class StepSerializer(CreateWithParentModelSerializer): id = serializers.UUIDField(format='hex', required=False) environment = RequestedEnvironmentSerializer() resources = RequestedResourceSetSerializer() inputs = StepInputSerializer(many=True, required=False) fixed_inputs = FixedStepInputSerializer(many=True, required=False) outputs = StepOutputSerializer(many=True) workflow_import = WorkflowImportSerializer(allow_null=True, required=False) class Meta: model = Step fields = ( 'id', 'name', 'command', 'environment', 'resources', 'inputs', 'fixed_inputs', 'outputs', 'datetime_created', 'workflow_import', ) def create(self, validated_data): data = copy.deepcopy(validated_data) # Can't create inputs, outputs, environment, or resources until # step exists. inputs = self.initial_data.get('inputs', None) fixed_inputs = self.initial_data.get('fixed_inputs', None) outputs = self.initial_data.get('outputs', None) resources = self.initial_data.get('resources', None) environment = self.initial_data.get('environment', None) workflow_import = self.initial_data.get('workflow_import', None) data.pop('inputs', None) data.pop('fixed_inputs', None) data.pop('outputs', None) data.pop('resources', None) data.pop('environment', None) data.pop('workflow_import', None) step = super(StepSerializer, self).create(data) if inputs is not None: for input_data in inputs: s = StepInputSerializer(data=input_data, context={ 'parent_field': 'step', 'parent_instance': step }) s.is_valid(raise_exception=True) s.save() if fixed_inputs is not None: for fixed_input_data in fixed_inputs: s = FixedStepInputSerializer(data=fixed_input_data, context={ 'parent_field': 'step', 'parent_instance': step }) s.is_valid(raise_exception=True) s.save() for output_data in outputs: s = StepOutputSerializer(data=output_data, context={ 'parent_field': 'step', 'parent_instance': step }) s.is_valid(raise_exception=True) s.save() if resources is not None: s = RequestedResourceSetSerializer(data=resources, context={ 'parent_field': 'step', 'parent_instance': step }) s.is_valid(raise_exception=True) s.save() if environment is not None: s = RequestedEnvironmentSerializer(data=environment, context={ 'parent_field': 'step', 'parent_instance': step }) s.is_valid(raise_exception=True) s.save() if workflow_import is not None: s = WorkflowImportSerializer(data=workflow_import, context={ 'parent_field': 'workflow', 'parent_instance': step }) s.is_valid(raise_exception=True) s.save() return step
class UnverifyModeratedObjectSerializer(serializers.Serializer): moderated_object_id = serializers.UUIDField( validators=[moderated_object_id_exists], required=True, )
class JobSerializer(serializers.Serializer): """ Return a full representation of an export Job. This is the core representation of the API. """ provider_tasks = ProviderTaskSerializer(many=True) uid = serializers.UUIDField(read_only=True) url = serializers.HyperlinkedIdentityField(view_name='api:jobs-detail', lookup_field='uid') name = serializers.CharField(max_length=100, ) description = serializers.CharField(max_length=255, ) event = serializers.CharField(max_length=100, allow_blank=True, required=False) created_at = serializers.DateTimeField(read_only=True) updated_at = serializers.DateTimeField(read_only=True) owner = serializers.SerializerMethodField(read_only=True) permissions = serializers.SerializerMethodField(read_only=True) relationship = serializers.SerializerMethodField(read_only=True) exports = serializers.SerializerMethodField() preset = serializers.PrimaryKeyRelatedField( queryset=DatamodelPreset.objects.all(), required=False) published = serializers.BooleanField(required=False) visibility = serializers.CharField(required=False) featured = serializers.BooleanField(required=False) region = SimpleRegionSerializer(read_only=True) extent = serializers.SerializerMethodField(read_only=True) original_selection = serializers.SerializerMethodField(read_only=True) user = serializers.HiddenField(default=serializers.CurrentUserDefault()) tags = serializers.SerializerMethodField() include_zipfile = serializers.BooleanField(required=False, default=False) @staticmethod def create(validated_data, **kwargs): """Creates an export Job. :param **kwargs: """ return Job.objects.create(**validated_data) @staticmethod def update(instance, validated_data, **kwargs): """Not implemented as Jobs are cloned rather than updated. :param **kwargs: """ raise NotImplementedError def validate(self, data, **kwargs): """ Validates the data submitted during Job creation. See api/validators.py for validation code. """ user = data['user'] selection = validators.validate_selection(self.context['request'].data, user=user) data['the_geom'] = selection original_selection = validators.validate_original_selection( self.context['request'].data) data['original_selection'] = original_selection data.pop('provider_tasks') return data @staticmethod def get_extent(obj): """Return the export extent as a GeoJSON Feature.""" uid = str(obj.uid) name = obj.name geom = obj.the_geom geometry = json.loads(GEOSGeometry(geom).geojson) feature = OrderedDict() feature['type'] = 'Feature' feature['properties'] = {'uid': uid, 'name': name} feature['geometry'] = geometry return feature @staticmethod def get_original_selection(obj): geom_collection = obj.original_selection if not geom_collection: return None feature_collection = OrderedDict() feature_collection['type'] = 'FeatureCollection' feature_collection['features'] = [] for geom in geom_collection: geojson_geom = json.loads(geom.geojson) feature = OrderedDict() feature['type'] = 'Feature' feature['geometry'] = geojson_geom feature_collection['features'].append(feature) return feature_collection def get_exports(self, obj): """Return the export formats selected for this export.""" exports = [] for provider_task in obj.provider_tasks.all(): serializer = ExportFormatSerializer( provider_task.formats, many=True, context={'request': self.context['request']}) exports.append({ "provider": provider_task.provider.name, "formats": serializer.data }) return exports def get_provider_tasks(self, obj): """Return the export formats selected for this export.""" exports = [] for provider_task in obj.provider_tasks.all(): serializer = ProviderTaskSerializer( provider_task.formats, many=True, context={'request': self.context['request']}) exports.append({provider_task.provider.name: serializer.data}) return exports def get_providers(self, obj): """Return the export formats selected for this export.""" providers = [ provider_format for provider_format in obj.providers.all() ] serializer = DataProviderSerializer( providers, many=True, context={'request': self.context['request']}) return serializer.data @staticmethod def get_tags(obj): """Return the Tags selected for this export.""" return obj.json_tags @staticmethod def get_owner(obj): """Return the username for the owner of this export.""" return obj.user.username def get_relationship(self, obj): request = self.context['request'] user = request.user return JobPermission.get_user_permissions(user, obj.uid) @staticmethod def get_permissions(obj): permissions = JobPermission.jobpermissions(obj) permissions['value'] = obj.visibility return permissions
class InsecureCommandAlertSerializer(serializers.Serializer): input = serializers.CharField() asset = serializers.CharField() user = serializers.CharField() risk_level = serializers.IntegerField() session = serializers.UUIDField()
class TreeObjectSerializer(serializers.Serializer): id = serializers.UUIDField() name = serializers.CharField()
class TestSerializer(serializers.Serializer): message = serializers.UUIDField(default=uuid.uuid4)
class NewCropperSerialier(serializers.Serializer): ''' ''' uuid = serializers.UUIDField(required=True)
class TestSerializer(serializers.Serializer): message = serializers.UUIDField(required=False)
class RoleSerializer(serializers.ModelSerializer): """Serializer for the Role model.""" uuid = serializers.UUIDField(read_only=True) name = serializers.CharField( required=True, max_length=150, validators=[UniqueValidator(queryset=Role.objects.all())]) description = serializers.CharField(allow_null=True, required=False) access = AccessSerializer(many=True) policyCount = serializers.IntegerField(read_only=True) accessCount = serializers.IntegerField(read_only=True) applications = serializers.SerializerMethodField() system = serializers.BooleanField(read_only=True) platform_default = serializers.BooleanField(read_only=True) created = serializers.DateTimeField(read_only=True) modified = serializers.DateTimeField(read_only=True) class Meta: """Metadata for the serializer.""" model = Role fields = ( "uuid", "name", "description", "access", "policyCount", "accessCount", "applications", "system", "platform_default", "created", "modified", ) def get_applications(self, obj): """Get the list of applications in the role.""" obtain_applications(obj) def create(self, validated_data): """Create the role object in the database.""" name = validated_data.pop("name") description = validated_data.pop("description", None) access_list = validated_data.pop("access") role = Role.objects.create(name=name, description=description) role.save() for access_item in access_list: resource_def_list = access_item.pop("resourceDefinitions") access_obj = Access.objects.create(**access_item, role=role) access_obj.save() for resource_def_item in resource_def_list: res_def = ResourceDefinition.objects.create(** resource_def_item, access=access_obj) res_def.save() return role def update(self, instance, validated_data): """Update the role object in the database.""" if instance.system: key = "role.update" message = "System roles may not be updated." error = {key: [_(message)]} raise serializers.ValidationError(error) access_list = validated_data.pop("access") instance.name = validated_data.get("name", instance.name) instance.description = validated_data.get("description", instance.description) instance.save() instance.access.all().delete() for access_item in access_list: resource_def_list = access_item.pop("resourceDefinitions") access_obj = Access.objects.create(**access_item, role=instance) access_obj.save() for resource_def_item in resource_def_list: res_def = ResourceDefinition.objects.create(** resource_def_item, access=access_obj) res_def.save() instance.save() return instance
def _test_format(self, uuid_format, formatted_uuid_0): field = serializers.UUIDField(format=uuid_format) assert field.to_representation(uuid.UUID(int=0)) == formatted_uuid_0 assert field.to_internal_value(formatted_uuid_0) == uuid.UUID(int=0)
class IPerfTestSerializer(serializers.ModelSerializer): benchmark_uuid = serializers.UUIDField() config = IPerfConfigSerializer() result = IPerfResultSerializer() class Meta: model = IPerfTest fields = ( "benchmark_uuid", "protocol_info", "config", "result", "order", "start_time", "wait_time", "duration", "wifi_bytes_received", "wifi_bytes_sent", "cell_bytes_received", "cell_bytes_sent", "multipath_service", "protocol", ) def create(self, validated_data): benchmark_uuid = validated_data.pop('benchmark_uuid') config_data = validated_data.pop("config") result_data = validated_data.pop("result") benchmark = Benchmark.objects.get(uuid=benchmark_uuid) config, _ = IPerfConfig.objects.get_or_create(**config_data) test = IPerfTest.objects.create(benchmark=benchmark, config=config, **validated_data) intervals_data = result_data.pop("intervals") result = IPerfResult.objects.create(test=test, **result_data) for i_data in intervals_data: IPerfInterval.objects.create(result=result, **i_data) protocol_info_db.delay("iperf", test.id) return test def to_representation(self, obj): infos = obj.protocol_info data_dict = {} cid = None for info in infos: cids_dict = info.get("Connections", {}) if len(cids_dict) == 0: continue if not cid: cid = list(cids_dict)[0] cid_dict = cids_dict.get(cid, {}) paths_dict = cid_dict.get("Paths", {}) for path_id in list(paths_dict): path_dict = paths_dict[path_id] if path_id not in data_dict: label = "Path " + path_id if_name = str(path_dict.get("InterfaceName", "")) if if_name: if if_name.startswith("en") or \ if_name.startswith("wlan"): label += " (WiFi)" elif if_name.startswith("pdp_ip") or \ if_name.startswith("rmnet"): label += " (Cellular)" else: label += " (" + if_name + ")" label += " Congestion Window" data_dict[path_id] = { "label": label, "values": [], } cwin = int(path_dict["CongestionWindow"]) timestamp = info["Time"] data_dict[path_id]["values"].append((timestamp, cwin)) data_list = [] for path_id in sorted(list(data_dict)): # In MPQUIC, don't log path 0 if int(path_id) == 0 and len(data_dict) > 1: continue data_list.append(data_dict[path_id]) return { "config": IPerfConfigSerializer(obj.config).data, "result": IPerfResultSerializer(obj.result).data, "graphs": [ { "x_label": "Time", "y_label": "Bytes", "data": data_list, }, ], "order": obj.order, "start_time": obj.start_time, "wait_time": obj.wait_time, "duration": obj.duration, "wifi_bytes_received": obj.wifi_bytes_received, "wifi_bytes_sent": obj.wifi_bytes_sent, "cell_bytes_received": obj.cell_bytes_received, "cell_bytes_sent": obj.cell_bytes_sent, "multipath_service": obj.multipath_service, "protocol": obj.protocol, }
class CreateSerializer(serializers.Serializer): id = serializers.UUIDField()