class AbstractReportSliceSerializer(ModelSerializer): """Abstract serializer for the ReportSlice models.""" report_platform_id = UUIDField(format='hex_verbose', required=False) report_slice_id = UUIDField(format='hex_verbose', required=False) account = CharField(max_length=50, required=False) report_json = JSONField(allow_null=False) git_commit = CharField(max_length=50, required=False) source = CharField(max_length=15, required=True) source_metadata = JSONField(allow_null=True, required=False) state = ChoiceField(choices=ReportSlice.STATE_CHOICES) retry_type = ChoiceField(choices=ReportSlice.RETRY_CHOICES, default=ReportSlice.TIME) state_info = JSONField(allow_null=False) retry_count = IntegerField(default=0) hosts_count = IntegerField(min_value=1, max_value=MAX_HOSTS_PER_REP) last_update_time = DateTimeField(allow_null=False) failed_hosts = JSONField(allow_null=True) candidate_hosts = JSONField(allow_null=True) ready_to_archive = BooleanField(default=False) creation_time = DateTimeField(allow_null=False) processing_start_time = DateTimeField(allow_null=True, required=False) processing_end_time = DateTimeField(allow_null=True, required=False) class Meta: """Meta class for AbstractReportSliceSerializer.""" abstract = True fields = '__all__'
class JobPostListingTagPostSerializer(serializers.ModelSerializer): job_post = PrimaryKeyRelatedField(pk_field=UUIDField(format='hex'), queryset=JobPost.objects.all()) listing_tag = PrimaryKeyRelatedField(pk_field=UUIDField(format='hex'), queryset=ListingTag.objects.all()) class Meta: model = JobPostListingTag fields = '__all__'
class ScrapeJobBoardPostSerializer(serializers.ModelSerializer): scrape = PrimaryKeyRelatedField(pk_field=UUIDField(format='hex'), queryset=Scrape.objects.all()) job_board = PrimaryKeyRelatedField(pk_field=UUIDField(format='hex'), queryset=JobBoard.objects.all()) class Meta: model = ScrapeJobBoard fields = '__all__'
class JobPostScrapePostSerializer(serializers.ModelSerializer): job_post = PrimaryKeyRelatedField(pk_field=UUIDField(format='hex'), queryset=JobPost.objects.all()) scrape = PrimaryKeyRelatedField(pk_field=UUIDField(format='hex'), queryset=Scrape.objects.all()) class Meta: model = JobPostScrape fields = '__all__'
class JobPostTechnologyPostSerializer(serializers.ModelSerializer): job_post = PrimaryKeyRelatedField(pk_field=UUIDField(format='hex'), queryset=JobPost.objects.all()) technology = PrimaryKeyRelatedField(pk_field=UUIDField(format='hex'), queryset=Technology.objects.all()) class Meta: model = JobPostTechnology fields = '__all__'
class PaymentSerializer(ModelSerializer): id = UUIDField(read_only=True) attributes = PaymentAttributesSerializer(allow_null=False) organisation_id = UUIDField(allow_null=False) version = IntegerField(min_value=0) class Meta: model = Payment fields = ('id', 'attributes', 'organisation_id', 'version') def create(self, validated_payment: dict): return Payment.objects.create(**validated_payment) def update(self, db_payment: Payment, validated_payment: dict): if "attributes" in validated_payment: attributes = validated_payment.pop("attributes") if "charges_information" in attributes: charges_information = attributes.pop("charges_information") db_payment.attributes['charges_information'].update( **charges_information) db_payment.attributes.update(**attributes) for key, value in validated_payment.items(): setattr(db_payment, key, value) db_payment.save() return db_payment
class AbstractReportSerializer(ModelSerializer): """Abstract serializer for the Report models.""" report_platform_id = UUIDField(format='hex_verbose', required=False) source = UUIDField(format='hex_verbose', required=False) source_metadata = JSONField(allow_null=True, required=False) account = CharField(max_length=50, required=False) request_id = CharField(max_length=50, required=False) upload_ack_status = CharField(max_length=10, required=False) upload_srv_kafka_msg = JSONField(required=True) git_commit = CharField(max_length=50, required=False) state = ChoiceField(choices=Report.STATE_CHOICES) retry_type = ChoiceField(choices=Report.RETRY_CHOICES, default=Report.TIME) state_info = JSONField(allow_null=True) retry_count = IntegerField(default=0) last_update_time = DateTimeField(allow_null=True) ready_to_archive = BooleanField(default=False) arrival_time = DateTimeField(allow_null=False) processing_start_time = DateTimeField(allow_null=True, required=False) processing_end_time = DateTimeField(allow_null=True, required=False) class Meta: """Meta class for ReportSerializer.""" abstract = True fields = '__all__'
class CompanyTechnologyPostSerializer(serializers.ModelSerializer): company = PrimaryKeyRelatedField(pk_field=UUIDField(format='hex'), queryset=Company.objects.all()) technology = PrimaryKeyRelatedField(pk_field=UUIDField(format='hex'), queryset=Technology.objects.all()) class Meta: model = CompanyTechnology fields = '__all__'
class AssetSerializer(ModelSerializer): id = UUIDField(source="external_id", read_only=True) status = ChoiceField(choices=Asset.StatusChoices, read_only=True) asset_type = ChoiceField(choices=Asset.AssetTypeChoices) location_object = AssetLocationSerializer(source="current_location", read_only=True) location = UUIDField(write_only=True, required=True) class Meta: model = Asset exclude = ("deleted", "external_id", "current_location") read_only_fields = TIMESTAMP_FIELDS def validate(self, attrs): user = self.context["request"].user if "location" in attrs: location = get_object_or_404( AssetLocation.objects.filter(external_id=attrs["location"])) facilities = get_facility_queryset(user) if not facilities.filter(id=location.facility.id).exists(): raise PermissionError() del attrs["location"] attrs["current_location"] = location return super().validate(attrs) def update(self, instance, validated_data): user = self.context["request"].user with transaction.atomic(): if "current_location" in validated_data: if instance.current_location != validated_data[ "current_location"]: if instance.current_location.facility.id != validated_data[ "current_location"].facility.id: raise ValidationError({ "location": "Interfacility transfer is not allowed here" }) AssetTransaction( from_location=instance.current_location, to_location=validated_data["current_location"], asset=instance, performed_by=user, ).save() updated_instance = super().update(instance, validated_data) return updated_instance
class RateDetails(Serializer): id = UUIDField(required=False, help_text="A unique rate identifier") carrier_name = CharField(required=True, help_text="The rate's carrier") carrier_id = CharField( required=True, help_text="The targeted carrier's name (unique identifier)") currency = CharField(required=True, help_text="The rate monetary values currency code") service = CharField(required=False, help_text="The carrier's rate (quote) service") discount = FloatField( required=False, help_text="The monetary amount of the discount on the rate") base_charge = FloatField(default=0.0, help_text=""" The rate's monetary amount of the base charge. This is the net amount of the rate before additional charges """) total_charge = FloatField(default=0.0, help_text=""" The rate's monetary amount of the total charge. This is the gross amount of the rate after adding the additional charges """) duties_and_taxes = FloatField( required=False, help_text="The monetary amount of the duties and taxes if applied") estimated_delivery = CharField(required=False, help_text="The estimated delivery date") extra_charges = ListField( child=ChargeDetails(), required=False, help_text="list of the rate's additional charges")
class SystemFactsSerializer(NotEmptySerializer): """Serializer for the SystemFacts model.""" connection_host = CharField(required=False, max_length=256) connection_port = IntegerField(required=False, min_value=0) connection_uuid = UUIDField(required=True) cpu_count = IntegerField(required=False, min_value=0) cpu_core_per_socket = IntegerField(required=False, min_value=0) cpu_siblings = IntegerField(required=False, min_value=0) cpu_hyperthreading = NullBooleanField(required=False) cpu_socket_count = IntegerField(required=False, min_value=0) cpu_core_count = IntegerField(required=False, min_value=0) date_anaconda_log = DateField(required=False) date_yum_history = DateField(required=False) etc_release_name = CharField(required=True, max_length=64) etc_release_version = CharField(required=True, max_length=64) etc_release_release = CharField(required=True, max_length=128) virt_virt = CharField(required=False, max_length=64) virt_type = CharField(required=False, max_length=64) virt_num_guests = IntegerField(required=False, min_value=0) virt_num_running_guests = IntegerField(required=False, min_value=0) virt_what_type = CharField(required=False, max_length=64) class Meta: """Meta class for SystemFactsSerializer.""" model = SystemFacts exclude = ('id', )
class ContactSerializer(ModelSerializer): forest_internal_id = CharField(read_only=True) forest_id = UUIDField(read_only=True) forestcustomer_id = UUIDField(read_only=True) customer_id = UUIDField(read_only=True) owner_customer_id = UUIDField(read_only=True) cc_attrs = JSONField(read_only=True) # forest customer contact default default = BooleanField(read_only=True) is_basic = BooleanField(read_only=True) forests_count = IntegerField(read_only=True) business_id = CharField(read_only=True) class Meta: model = Contact exclude = ["contact_info", "deleted"]
class FingerprintSerializer(NotEmptySerializer): """Serializer for the Fingerprint model.""" os_name = CharField(required=True, max_length=64) os_release = CharField(required=True, max_length=128) os_version = CharField(required=True, max_length=64) connection_host = CharField(required=False, max_length=256) connection_port = IntegerField(required=False, min_value=0) connection_uuid = UUIDField(required=True) cpu_count = IntegerField(required=False, min_value=0) cpu_core_per_socket = IntegerField(required=False, min_value=0) cpu_siblings = IntegerField(required=False, min_value=0) cpu_hyperthreading = NullBooleanField(required=False) cpu_socket_count = IntegerField(required=False, min_value=0) cpu_core_count = IntegerField(required=False, min_value=0) system_creation_date = DateField(required=False) infrastructure_type = ChoiceField( required=True, choices=SystemFingerprint.INFRASTRUCTURE_TYPE) virtualized_is_guest = NullBooleanField(required=True) virtualized_type = CharField(required=False, max_length=64) virtualized_num_guests = IntegerField(required=False, min_value=0) virtualized_num_running_guests = IntegerField(required=False, min_value=0) class Meta: """Meta class for FingerprintSerializer.""" model = SystemFingerprint fields = '__all__'
class UserRegisterSerializer(ModelSerializer): """Serializers signup requests and creates a new user.""" u_id = UUIDField(read_only=True) # Ensure passwords are at least 8 characters long, no longer than 128 # characters, and can not be read by the client. password = CharField(max_length=128, min_length=8, write_only=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields: # Iterate over the serializer fields. # Set the custom error message. self.fields[field].error_messages['required'] = \ f'Field `{field}` is required for `user` data.' class Meta: model = User # List all of the fields that could possibly be included in a request # or response, including fields specified explicitly above. fields = ( 'id', 'u_id', 'first_name', 'last_name', 'email', 'password', 'token', ) def create(self, validated_data): return User.objects.create_user(**validated_data)
def destroy(self, request, *args, **kwargs): """Delete a provider. @api {delete} /cost-management/v1/providers/:uuid/ Delete a provider @apiName DeleteProvider @apiGroup Provider @apiVersion 1.0.0 @apiDescription Delete a provider. @apiHeader {String} token Authorization token of an authenticated user @apiParam {String} uuid Provider unique ID. @apiSuccessExample {json} Success-Response: HTTP/1.1 204 NO CONTENT """ # Block any users not part of the organization if not self.get_queryset(): raise PermissionDenied() # throws ValidationError if pk is not a valid UUID uuid = UUIDField().to_internal_value(data=kwargs.get('uuid')) get_object_or_404(Provider, uuid=uuid) manager = ProviderManager(uuid) try: manager.remove(request.user) except Exception: LOG.error('{} failed to remove provider uuid: {}.'.format( request.user, uuid)) raise ProviderDeleteException return Response(status=status.HTTP_204_NO_CONTENT)
class DeploymentReportSerializer(NotEmptySerializer): """Serializer for the Fingerprint model.""" # Scan information report_type = CharField(read_only=True) report_version = CharField(max_length=64, read_only=True) report_platform_id = UUIDField(format='hex_verbose', read_only=True) details_report = PrimaryKeyRelatedField( queryset=DetailsReport.objects.all()) report_id = IntegerField(read_only=True) cached_fingerprints = CustomJSONField(read_only=True) cached_masked_fingerprints = CustomJSONField(read_only=True) cached_csv = CharField(read_only=True) cached_masked_csv = CharField(read_only=True) cached_insights = CharField(read_only=True) status = ChoiceField(read_only=True, choices=DeploymentsReport.STATUS_CHOICES) system_fingerprints = FingerprintField(many=True, read_only=True) class Meta: """Meta class for DeploymentReportSerializer.""" model = DeploymentsReport fields = '__all__'
class ImageSerializer(Serializer): uuid = UUIDField() width = IntegerField() height = IntegerField() size = IntegerField() type = CharField() color = CharField()
class UserSkillSerializer(ModelSerializer): id = UUIDField(source="external_id", read_only=True) skill = ExternalIdSerializerField(write_only=True, required=True, queryset=Skill.objects.all()) skill_object = SkillSerializer(source="skill", read_only=True) class Meta: model = UserSkill fields = ("id", "skill", "skill_object")
class AssetLocationSerializer(ModelSerializer): facility = FacilityBareMinimumSerializer(read_only=True) id = UUIDField(source="external_id", read_only=True) class Meta: model = AssetLocation exclude = ("deleted", "external_id") read_only_fields = TIMESTAMP_FIELDS
class UserLoginSerializer(Serializer): id_ = IntegerField(read_only=True) u_id = UUIDField(read_only=True) first_name = CharField(read_only=True) last_name = CharField(read_only=True) email = CharField(max_length=255) token = CharField(max_length=255, read_only=True) password = CharField(max_length=128, write_only=True) def validate(self, data): # The `validate` method is where we make sure that the current # instance of `LoginSerializer` has "valid". In the case of logging a # user in, this means validating that they've provided an email # and password and that this combination matches one of the users in # our database. email = data.get('email', None) password = data.get('password', None) # Raise an exception if an email is not provided. if not email: raise ValidationError('email is required to log in') # Raise an exception if the password is not provided. if not password: raise ValidationError('password is required to log in') # The `authenticate` method is provided by Django and handles checking # for a user that matches this email/password combination. Notice how # we pass `email` as the `username` value since in our User # model we set `USERNAME_FIELD` as `email`. user = authenticate(username=email, password=password) # If no user was found matching this email/password combination then # `authenticate` will return `None`. Raise an exception in this case. if not user: raise ValidationError( 'user with this email and password was not found') # Django provides a flag on our `User` model called `is_active`. The # purpose of this flag is to tell us whether the user has been banned # or deactivated. This will almost never be the case, but # it is worth checking. Raise an exception in this case. if not user.is_active: raise ValidationError('this user has been deactivated') # The `validate` method should return a dictionary of validated data. # This is the data that is passed to the `create` and `update` methods # that we will see later on. return dict( id_=user.id, u_id=user.u_id, first_name=user.first_name, last_name=user.last_name, email=user.email, token=user.token, )
class AssetTransactionSerializer(ModelSerializer): id = UUIDField(source="external_id", read_only=True) asset = AssetBareMinimumSerializer(read_only=True) from_location = AssetLocationSerializer(read_only=True) to_location = AssetLocationSerializer(read_only=True) performed_by = UserBaseMinimumSerializer(read_only=True) class Meta: model = AssetTransaction exclude = ("deleted", "external_id")
class CustomerContactSerializer(ModelSerializer): customer_id = UUIDField(read_only=True) customer_name_kanji = JSONField(read_only=True) cc_attrs = JSONField(read_only=True) is_basic = BooleanField(read_only=True) forests_count = IntegerField(read_only=True) business_id = CharField(read_only=True) class Meta: model = Contact exclude = ["contact_info", "deleted"]
class ShipmentDetails(Serializer): id = UUIDField(required=False, help_text="A unique shipment identifier") carrier_name = CharField(required=True, help_text="The shipment carrier") carrier_id = CharField( required=True, help_text="The shipment carrier configured identifier") label = CharField(required=True, help_text="The shipment label in base64 string") tracking_number = CharField(required=True, help_text="The shipment tracking number") selected_rate = RateDetails(required=False, help_text="The shipment selected rate")
def update(self, request, *args, **kwargs): """Update a Provider.""" if request.method == 'PATCH': raise ProviderMethodException('PATCH not supported') user = request.user uuid = UUIDField().to_internal_value(data=kwargs.get('uuid')) get_object_or_404(Provider, uuid=uuid, customer=user.customer) manager = ProviderManager(kwargs['uuid']) manager.update(request) return super().update(request=request, args=args, kwargs=kwargs)
class UserJwtSerializer(AbstractJwtSerializer): user_uuid = UUIDField(source='user_id') identity_token = CharField(max_length=40) elevated_token = CharField(max_length=40) user_permissions = ListField(child=CharField(max_length=120)) service_permissions = ListField(child=CharField(max_length=120)) is_loggedin = SerializerMethodField() def get_is_user(self, obj): return True @staticmethod def get_is_loggedin(obj): return obj.identity_token and obj.elevated_token
class SummarySiteSerializer(GeoFeatureModelSerializer): site_id = UUIDField(required=False) site_name = CharField(required=False) project_id = UUIDField(required=False) project_name = CharField(required=False) country_id = UUIDField(required=False) country_name = CharField(required=False) contact_link = CharField(required=False) data_policy_beltfish = CharField(required=False) data_policy_benthiclit = CharField(required=False) data_policy_benthicpit = CharField(required=False) data_policy_habitatcomplexity = CharField(required=False) data_policy_bleachingqc = CharField(required=False) reef_type = CharField(required=False) reef_zone = CharField(required=False) exposure = CharField(required=False) point = SerializerMethodField() # lat = DecimalField(max_digits=16, decimal_places=14, coerce_to_string=False, required=False) # lon = DecimalField(max_digits=17, decimal_places=14, coerce_to_string=False, required=False) def get_point(self, obj): return {'type': 'Point', 'coordinates': [obj.lon, obj.lat]} class Meta: model = SummarySiteView geo_field = 'point' coord_precision = 6 # to nearest 10cm fields = [ 'site_id', 'site_name', 'site_notes', 'project_id', 'project_name', 'project_notes', 'country_id', 'country_name', 'contact_link', 'data_policy_beltfish', 'data_policy_benthiclit', 'data_policy_benthicpit', 'data_policy_habitatcomplexity', 'data_policy_bleachingqc', 'reef_type', 'reef_zone', 'exposure', 'tags', 'project_admins', 'date_min', 'date_max', 'depth', 'management_regimes', 'protocols' ]
class ShipmentRequest(Serializer): selected_rate_id = UUIDField( required=True, help_text="The selected shipment rate unique identifier") rates = ListField( child=RateDetails(), help_text="The list for shipment rates fetched previously") shipper = ShipmentShipperAddress( required=True, help_text="The origin address of the shipment (address from)") recipient = ShipmentRecipientAddress( required=True, help_text="The shipment destination address (address to)") parcel = Parcel(required=True, help_text="The shipment's parcel") services = StringListField(required=False, help_text=""" The requested carrier service for the shipment. Please consult the reference for specific carriers services. Note that this is a list because on a Multi-carrier rate request you could specify a service per carrier. """) options = DictField(required=False, help_text=""" The options available for the shipment. Please consult the reference for additional specific carriers options. """) payment = Payment(required=True, help_text="The payment details") customs = Customs(required=False, help_text=""" The customs details. Note that this is required for the shipment of an international Dutiable parcel. """) doc_images = ListField(child=Doc(), required=False, help_text=""" The list of documents to attach for a paperless interantional trade. eg: Invoices... """) reference = CharField(required=False, help_text="The shipment reference")
def destroy(self, request, *args, **kwargs): """Delete a provider.""" # throws ValidationError if pk is not a valid UUID user = request.user uuid = UUIDField().to_internal_value(data=kwargs.get('uuid')) get_object_or_404(Provider, uuid=uuid, customer=user.customer) manager = ProviderManager(uuid) try: manager.remove(request) except Exception as error: LOG.error( f'{request.user} failed to remove provider uuid: {uuid}. Error: {str(error)}' ) raise ProviderDeleteException return Response(status=status.HTTP_204_NO_CONTENT)
class DetailsReportSerializer(NotEmptySerializer): """Serializer for the DetailsReport model.""" report_type = CharField(read_only=True) report_version = CharField(max_length=64, read_only=True) sources = CustomJSONField(required=True) report_id = IntegerField(read_only=True) report_platform_id = UUIDField(format='hex_verbose', read_only=True) cached_csv = CharField(required=False, read_only=True) class Meta: """Meta class for DetailsReportSerializer.""" model = DetailsReport exclude = ('id', 'deployment_report')
class NewsSerializer(ModelSerializer): uid = UUIDField(source='uuid') updateDate = DateTimeField(source='created') titleText = CharField(source='title') streamUrl = CharField(source='audio_url') mainText = CharField(source='content') redirectionUrl = SerializerMethodField('get_redirection') def get_redirection(self, obj): return RADIO_LINK_BASE + obj.external_id class Meta: model = News fields = [ 'uid', 'updateDate', 'titleText', 'streamUrl', 'mainText', 'redirectionUrl' ]