-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathserializers.py
More file actions
967 lines (874 loc) · 33.7 KB
/
Copy pathserializers.py
File metadata and controls
967 lines (874 loc) · 33.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
import logging
import os
import tempfile
from gettext import gettext as _
from urllib.parse import urljoin
from django.conf import settings
from django.db.utils import IntegrityError
from drf_spectacular.utils import extend_schema_serializer
from packaging.requirements import Requirement
from packaging.version import InvalidVersion, Version
from pydantic import TypeAdapter
from pydantic import ValidationError as PydanticValidationError
from pypi_attestations import AttestationError
from rest_framework import serializers
from pulpcore.plugin import models as core_models
from pulpcore.plugin import serializers as core_serializers
from pulpcore.plugin.util import get_current_authenticated_user, get_domain, get_prn, reverse
from pulp_python.app import models as python_models
from pulp_python.app.provenance import (
AnyPublisher,
Attestation,
AttestationBundle,
Provenance,
verify_provenance,
)
from pulp_python.app.utils import (
DIST_EXTENSIONS,
artifact_to_metadata_artifact,
artifact_to_python_content_data,
canonicalize_name,
get_project_metadata_from_file,
parse_project_metadata,
)
log = logging.getLogger(__name__)
PYPI_BASE_URL = urljoin(settings.PYPI_API_HOSTNAME, settings.PYPI_PATH_PREFIX)
@extend_schema_serializer(
deprecate_fields=[
"autopublish",
]
)
class PythonRepositorySerializer(core_serializers.RepositorySerializer):
"""
Serializer for Python Repositories.
"""
autopublish = serializers.BooleanField(
help_text=_(
"Whether to automatically create publications for new repository versions, "
"and update any distributions pointing to this repository. [Deprecated]"
),
default=False,
required=False,
)
blocklist_entries_href = serializers.SerializerMethodField(
help_text=_("URL to the blocklist entries for this repository."),
read_only=True,
)
allow_package_substitution = serializers.BooleanField(
help_text=_(
"Whether to allow package substitution (replacing existing packages with packages "
"that have the same filename but a different checksum). When False, any new "
"repository version that would cause such a substitution will be rejected. This "
"applies to all repository version creation paths including uploads, modify, and "
"sync. When True (the default), package substitution is allowed."
),
default=True,
required=False,
)
def get_blocklist_entries_href(self, obj):
repo_href = reverse("repositories-python/python-detail", kwargs={"pk": obj.pk})
return f"{repo_href}blocklist_entries/"
class Meta:
fields = core_serializers.RepositorySerializer.Meta.fields + (
"autopublish",
"allow_package_substitution",
"blocklist_entries_href",
)
model = python_models.PythonRepository
@extend_schema_serializer(
deprecate_fields=[
"publication",
]
)
class PythonDistributionSerializer(core_serializers.DistributionSerializer):
"""
Serializer for Pulp distributions for the Python type.
"""
publication = core_serializers.DetailRelatedField(
required=False,
help_text=_("Publication to be served. [Deprecated]"),
view_name_pattern=r"publications(-.*/.*)?-detail",
queryset=core_models.Publication.objects.exclude(complete=False),
allow_null=True,
)
repository_version = core_serializers.RepositoryVersionRelatedField(
required=False, help_text=_("RepositoryVersion to be served."), allow_null=True
)
base_url = serializers.SerializerMethodField(read_only=True)
allow_uploads = serializers.BooleanField(
default=True, help_text=_("Allow packages to be uploaded to this index.")
)
remote = core_serializers.DetailRelatedField(
required=False,
help_text=_("Remote that can be used to fetch content when using pull-through caching."),
view_name_pattern=r"remotes(-.*/.*)?-detail",
queryset=core_models.Remote.objects.all(),
allow_null=True,
)
def get_base_url(self, obj):
"""Gets the base url."""
if settings.DOMAIN_ENABLED:
return urljoin(PYPI_BASE_URL, f"{get_domain().name}/{obj.base_path}/")
return urljoin(PYPI_BASE_URL, f"{obj.base_path}/")
class Meta:
fields = core_serializers.DistributionSerializer.Meta.fields + (
"publication",
"repository_version",
"allow_uploads",
"remote",
)
model = python_models.PythonDistribution
class PythonSingleContentArtifactField(core_serializers.SingleContentArtifactField):
"""
Custom field with overridden get_attribute method. Meant to be used only in
PythonPackageContentSerializer to handle possible existence of metadata artifact.
"""
def get_attribute(self, instance):
# When content has multiple artifacts (wheel + metadata), return the main one
if instance._artifacts.count() > 1:
for ca in instance.contentartifact_set.all():
if not ca.relative_path.endswith(".metadata"):
return ca.artifact
return super().get_attribute(instance)
class PythonPackageContentSerializer(core_serializers.SingleArtifactContentUploadSerializer):
"""
A Serializer for PythonPackageContent.
"""
artifact = PythonSingleContentArtifactField(
help_text=_("Artifact file representing the physical content"),
)
# Core metadata
# Version 1.0
author = serializers.CharField(
required=False,
allow_blank=True,
help_text=_(
"Text containing the author's name. Contact information can also be added,"
" separated with newlines."
),
)
author_email = serializers.CharField(
required=False, allow_blank=True, help_text=_("The author's e-mail address. ")
)
description = serializers.CharField(
required=False,
allow_blank=True,
help_text=_("A longer description of the package that can run to several paragraphs."),
)
home_page = serializers.CharField(
required=False, allow_blank=True, help_text=_("The URL for the package's home page.")
)
keywords = serializers.CharField(
required=False,
allow_blank=True,
help_text=_(
"Additional keywords to be used to assist searching for the "
"package in a larger catalog."
),
)
license = serializers.CharField(
required=False,
allow_blank=True,
help_text=_("Text indicating the license covering the distribution"),
)
metadata_version = serializers.CharField(
help_text=_("Version of the file format"),
read_only=True,
)
name = serializers.CharField(
help_text=_("The name of the python project."),
read_only=True,
)
platform = serializers.CharField(
required=False,
allow_blank=True,
help_text=_(
"A comma-separated list of platform specifications, "
"summarizing the operating systems supported by the package."
),
)
summary = serializers.CharField(
required=False,
allow_blank=True,
help_text=_("A one-line summary of what the package does."),
)
version = serializers.CharField(
help_text=_("The packages version number."),
read_only=True,
)
# Version 1.1
classifiers = serializers.JSONField(
required=False,
default=list,
help_text=_("A JSON list containing classification values for a Python package."),
)
download_url = serializers.CharField(
required=False,
allow_blank=True,
help_text=_("Legacy field denoting the URL from which this package can be downloaded."),
)
supported_platform = serializers.CharField(
required=False,
allow_blank=True,
help_text=_("Field to specify the OS and CPU for which the binary package was compiled. "),
)
# Version 1.2
maintainer = serializers.CharField(
required=False,
allow_blank=True,
help_text=_(
"The maintainer's name at a minimum; additional contact information may be provided."
),
)
maintainer_email = serializers.CharField(
required=False, allow_blank=True, help_text=_("The maintainer's e-mail address.")
)
obsoletes_dist = serializers.JSONField(
required=False,
default=list,
help_text=_(
"A JSON list containing names of a distutils project's distribution which "
"this distribution renders obsolete, meaning that the two projects should not "
"be installed at the same time."
),
)
project_url = serializers.CharField(
required=False,
allow_blank=True,
help_text=_("A browsable URL for the project and a label for it, separated by a comma."),
)
project_urls = serializers.JSONField(
required=False,
default=dict,
help_text=_("A dictionary of labels and URLs for the project."),
)
provides_dist = serializers.JSONField(
required=False,
default=list,
help_text=_(
"A JSON list containing names of a Distutils project which is contained"
" within this distribution."
),
)
requires_external = serializers.JSONField(
required=False,
default=list,
help_text=_(
"A JSON list containing some dependency in the system that the distribution "
"is to be used."
),
)
requires_dist = serializers.JSONField(
required=False,
default=list,
help_text=_(
"A JSON list containing names of some other distutils project "
"required by this distribution."
),
)
requires_python = serializers.CharField(
required=False,
allow_blank=True,
help_text=_(
"The Python version(s) that the distribution is guaranteed to be compatible with."
),
)
# Version 2.1
description_content_type = serializers.CharField(
required=False,
allow_blank=True,
help_text=_(
"A string stating the markup syntax (if any) used in the distribution's"
" description, so that tools can intelligently render the description."
),
)
provides_extras = serializers.JSONField(
required=False,
default=list,
help_text=_("A JSON list containing names of optional features provided by the package."),
)
# Version 2.2
dynamic = serializers.JSONField(
required=False,
default=list,
help_text=_(
"A JSON list containing names of other core metadata fields which are "
"permitted to vary between sdist and bdist packages. Fields NOT marked "
"dynamic MUST be the same between bdist and sdist."
),
)
# Version 2.4
license_expression = serializers.CharField(
required=False,
allow_blank=True,
help_text=_("Text string that is a valid SPDX license expression."),
)
license_file = serializers.JSONField(
required=False,
default=list,
help_text=_("A JSON list containing names of the paths to license-related files."),
)
# Release metadata
filename = serializers.CharField(
help_text=_(
"The name of the distribution package, usually of the format:"
" {distribution}-{version}(-{build tag})?-{python tag}-{abi tag}"
"-{platform tag}.{packagetype}"
),
read_only=True,
)
packagetype = serializers.CharField(
help_text=_(
"The type of the distribution package (e.g. sdist, bdist_wheel, bdist_egg, etc)"
),
read_only=True,
)
python_version = serializers.CharField(
help_text=_(
"The tag that indicates which Python implementation or version the package requires."
),
read_only=True,
)
size = serializers.IntegerField(
help_text=_("The size of the package in bytes."),
read_only=True,
)
sha256 = serializers.CharField(
default="",
help_text=_("The SHA256 digest of this package."),
)
metadata_sha256 = serializers.CharField(
required=False,
allow_null=True,
help_text=_("The SHA256 digest of the package's METADATA file."),
)
# PEP740 Attestations/Provenance
attestations = serializers.JSONField(
required=False,
help_text=_("A JSON list containing attestations for the package."),
write_only=True,
)
provenance = serializers.SerializerMethodField(
read_only=True, help_text=_("The created provenance object on upload.")
)
def get_provenance(self, obj):
"""Get the provenance for the package."""
if provenance := getattr(obj, "provenance", None):
return get_prn(provenance)
return None
def validate_attestations(self, value):
"""Validate the attestations, turn into Attestation objects."""
try:
if isinstance(value, str):
attestations = TypeAdapter(list[Attestation]).validate_json(value)
else:
attestations = TypeAdapter(list[Attestation]).validate_python(value)
except PydanticValidationError as e:
raise serializers.ValidationError(_("Invalid attestations: {}").format(e))
return attestations
def handle_attestations(self, filename, sha256, attestations, offline=True):
"""Handle converting attestations to a Provenance object."""
user = get_current_authenticated_user()
publisher = AnyPublisher(kind="Pulp User", prn=get_prn(user))
att_bundle = AttestationBundle(publisher=publisher, attestations=attestations)
provenance = Provenance(attestation_bundles=[att_bundle])
try:
verify_provenance(filename, sha256, provenance, offline=offline)
except AttestationError as e:
raise serializers.ValidationError(
{"attestations": _("Attestations failed verification: {}").format(e)}
)
return provenance.model_dump(mode="json")
def deferred_validate(self, data):
"""
Validate the python package data.
Args:
data (dict): Data to be validated
Returns:
dict: Data that has been validated
"""
data = super().deferred_validate(data)
try:
filename = data["relative_path"]
except KeyError:
raise serializers.ValidationError(detail={"relative_path": _("This field is required")})
artifact = data["artifact"]
try:
_data = artifact_to_python_content_data(filename, artifact, domain=get_domain())
except ValueError:
raise serializers.ValidationError(
_(
"Extension on {} is not a valid python extension "
"(.whl, .exe, .egg, .tar.gz, .tar.bz2, .zip)"
).format(filename)
)
if data.get("sha256") and data["sha256"] != artifact.sha256:
raise serializers.ValidationError(
detail={
"sha256": _(
"The uploaded artifact's sha256 checksum does not match the one provided"
)
}
)
data.update(_data)
if attestations := data.pop("attestations", None):
data["provenance"] = self.handle_attestations(filename, data["sha256"], attestations)
# Create metadata artifact for wheel files
if filename.endswith(".whl"):
if metadata_artifact := artifact_to_metadata_artifact(filename, artifact):
data["metadata_artifact"] = metadata_artifact
data["metadata_sha256"] = metadata_artifact.sha256
return data
def get_artifacts(self, validated_data):
artifacts = super().get_artifacts(validated_data)
if metadata_artifact := validated_data.pop("metadata_artifact", None):
relative_path = f"{validated_data['filename']}.metadata"
artifacts[relative_path] = metadata_artifact
return artifacts
def retrieve(self, validated_data):
content = python_models.PythonPackageContent.objects.filter(
sha256=validated_data["sha256"], _pulp_domain=get_domain()
)
return content.first()
def create(self, validated_data):
"""Create new PythonPackageContent object."""
repository = validated_data.pop("repository", None)
provenance = validated_data.pop("provenance", None)
content = super().create(validated_data)
if provenance:
prov_sha256 = python_models.PackageProvenance.calculate_sha256(provenance)
prov_model, _created = python_models.PackageProvenance.objects.get_or_create(
sha256=prov_sha256,
_pulp_domain=get_domain(),
defaults={"package": content, "provenance": provenance},
)
if core_models.Task.current():
core_models.CreatedResource.objects.create(content_object=prov_model)
setattr(content, "provenance", prov_model)
if repository:
repository.cast()
content_to_add = [content.pk, content.provenance.pk] if provenance else [content.pk]
content_to_add = core_models.Content.objects.filter(pk__in=content_to_add)
with repository.new_version() as new_version:
new_version.add_content(content_to_add)
return content
class Meta:
fields = core_serializers.SingleArtifactContentUploadSerializer.Meta.fields + (
"artifact",
"author",
"author_email",
"description",
"home_page",
"keywords",
"license",
"metadata_version",
"name",
"platform",
"summary",
"version",
"classifiers",
"download_url",
"supported_platform",
"maintainer",
"maintainer_email",
"obsoletes_dist",
"project_url",
"project_urls",
"provides_dist",
"requires_external",
"requires_dist",
"requires_python",
"description_content_type",
"provides_extras",
"dynamic",
"license_expression",
"license_file",
"filename",
"packagetype",
"python_version",
"size",
"sha256",
"metadata_sha256",
"attestations",
"provenance",
)
model = python_models.PythonPackageContent
class PythonPackageContentUploadSerializer(PythonPackageContentSerializer):
"""
A serializer for requests to synchronously upload Python packages.
"""
def validate(self, data):
"""
Validates an uploaded Python package file, extracts its metadata,
and creates or retrieves an associated Artifact.
Returns updated data with artifact and metadata details.
"""
file = data.pop("file")
filename = file.name
for ext, packagetype in DIST_EXTENSIONS.items():
if filename.endswith(ext):
break
else:
raise serializers.ValidationError(
_(
"Extension on {} is not a valid python extension "
"(.whl, .exe, .egg, .tar.gz, .tar.bz2, .zip)"
).format(filename)
)
# Replace the incorrect file name in the file path with the original file name
original_filepath = file.file.name
path_to_file, tmp_str = original_filepath.rsplit("/", maxsplit=1)
tmp_str = tmp_str.split(".", maxsplit=1)[0] # Remove e.g. ".upload.gz" suffix
new_filepath = f"{path_to_file}/{tmp_str}{filename}"
os.rename(original_filepath, new_filepath)
metadata = get_project_metadata_from_file(new_filepath)
artifact = core_models.Artifact.init_and_validate(new_filepath)
try:
artifact.save()
except IntegrityError:
artifact = core_models.Artifact.objects.get(
sha256=artifact.sha256, pulp_domain=get_domain()
)
artifact.touch()
log.info(f"Artifact for {file.name} already existed in database")
data["artifact"] = artifact
data["sha256"] = artifact.sha256
data["relative_path"] = filename
data["size"] = artifact.size
data.update(parse_project_metadata(vars(metadata)))
# Overwrite filename from metadata
data["filename"] = filename
if attestations := data.pop("attestations", None):
data["provenance"] = self.handle_attestations(
filename, data["sha256"], attestations, offline=True
)
# Create metadata artifact for wheel files
if filename.endswith(".whl"):
with tempfile.TemporaryDirectory(dir=settings.WORKING_DIRECTORY) as temp_dir:
if metadata_artifact := artifact_to_metadata_artifact(
filename, artifact, tmp_dir=temp_dir
):
data["metadata_artifact"] = metadata_artifact
data["metadata_sha256"] = metadata_artifact.sha256
return data
class Meta(PythonPackageContentSerializer.Meta):
# This API does not support uploading to a repository or using a custom relative_path
fields = tuple(
f
for f in PythonPackageContentSerializer.Meta.fields
if f not in ["repository", "relative_path"]
)
model = python_models.PythonPackageContent
# Name used for the OpenAPI request object
ref_name = "PythonPackageContentUpload"
class MinimalPythonPackageContentSerializer(PythonPackageContentSerializer):
"""
A Serializer for PythonPackageContent.
"""
class Meta:
fields = core_serializers.SingleArtifactContentUploadSerializer.Meta.fields + (
"filename",
"packagetype",
"name",
"version",
"sha256",
)
model = python_models.PythonPackageContent
class PackageProvenanceSerializer(core_serializers.NoArtifactContentUploadSerializer):
"""
A Serializer for PackageProvenance.
"""
package = core_serializers.DetailRelatedField(
help_text=_("The package that the provenance is for."),
view_name_pattern=r"content(-.*/.*)-detail",
queryset=python_models.PythonPackageContent.objects.all(),
)
provenance = serializers.JSONField(read_only=True, default=dict)
sha256 = serializers.CharField(read_only=True)
verify = serializers.BooleanField(
default=True,
write_only=True,
help_text=_("Verify each attestation in the provenance."),
)
def deferred_validate(self, data):
"""
Validate that the provenance is valid and pointing to the correct package.
"""
data = super().deferred_validate(data)
try:
provenance = Provenance.model_validate_json(data["file"].read())
data["provenance"] = provenance.model_dump(mode="json")
except PydanticValidationError as e:
raise serializers.ValidationError(
_("The uploaded provenance is not valid: {}").format(e)
)
if data.pop("verify"):
try:
verify_provenance(data["package"].filename, data["package"].sha256, provenance)
except AttestationError as e:
raise serializers.ValidationError(_("Provenance verification failed: {}").format(e))
return data
def retrieve(self, validated_data):
sha256 = python_models.PackageProvenance.calculate_sha256(validated_data["provenance"])
content = python_models.PackageProvenance.objects.filter(
sha256=sha256, _pulp_domain=get_domain()
).first()
return content
class Meta:
fields = core_serializers.NoArtifactContentUploadSerializer.Meta.fields + (
"package",
"provenance",
"sha256",
"verify",
)
model = python_models.PackageProvenance
class MultipleChoiceArrayField(serializers.MultipleChoiceField):
"""
A wrapper to make sure this DRF serializer works properly with ArrayFields.
"""
def to_internal_value(self, data):
"""Converts set to list."""
return list(super().to_internal_value(data))
def to_representation(self, value):
"""Converts set to list for JSON serialization."""
result = super().to_representation(value)
if isinstance(result, set):
result = list(result)
return result
class PackageYankSerializer(core_serializers.NoArtifactContentSerializer):
"""
Read-only serializer for PackageYank content units (PEP 592).
Used by PackageYankViewSet to expose yank markers via the Pulp REST API.
"""
name_normalized = serializers.CharField(read_only=True)
version = serializers.CharField(read_only=True)
yanked_reason = serializers.CharField(read_only=True)
class Meta:
fields = core_serializers.NoArtifactContentSerializer.Meta.fields + (
"name_normalized",
"version",
"yanked_reason",
)
model = python_models.PackageYank
class PythonRemoteSerializer(core_serializers.RemoteSerializer):
"""
A Serializer for PythonRemote.
"""
includes = serializers.ListField(
child=serializers.CharField(allow_blank=False),
required=False,
allow_empty=True,
help_text=_("A list containing project specifiers for Python packages to include."),
)
excludes = serializers.ListField(
child=serializers.CharField(allow_blank=False),
required=False,
allow_empty=True,
help_text=_("A list containing project specifiers for Python packages to exclude."),
)
prereleases = serializers.BooleanField(
required=False, help_text=_("Whether or not to include pre-release packages in the sync.")
)
policy = serializers.ChoiceField(
help_text=_(
"The policy to use when downloading content. The possible values include: "
"'immediate', 'on_demand', and 'streamed'. 'on_demand' is the default."
),
choices=core_models.Remote.POLICY_CHOICES,
default=core_models.Remote.ON_DEMAND,
)
package_types = MultipleChoiceArrayField(
required=False,
help_text=_(
"The package types to sync for Python content. Leave blank to get everypackage type."
),
choices=python_models.PACKAGE_TYPES,
default=list,
)
keep_latest_packages = serializers.IntegerField(
required=False,
help_text=_(
"The amount of latest versions of a package to keep on sync, includes"
"pre-releases if synced. Default 0 keeps all versions."
),
default=0,
)
exclude_platforms = MultipleChoiceArrayField(
required=False,
help_text=_(
"List of platforms to exclude syncing Python packages for. Possible values"
"include: windows, macos, freebsd, and linux."
),
choices=python_models.PLATFORMS,
default=list,
)
provenance = serializers.BooleanField(
required=False,
help_text=_("Whether to sync available provenances for Python packages."),
default=False,
)
def validate_includes(self, value):
"""Validates the includes"""
for pkg in value:
try:
Requirement(pkg)
except ValueError as ve:
raise serializers.ValidationError(
_("includes specifier {} is invalid. {}").format(pkg, ve)
)
return value
def validate_excludes(self, value):
"""Validates the excludes"""
for pkg in value:
try:
Requirement(pkg)
except ValueError as ve:
raise serializers.ValidationError(
_("excludes specifier {} is invalid. {}").format(pkg, ve)
)
return value
class Meta:
fields = core_serializers.RemoteSerializer.Meta.fields + (
"includes",
"excludes",
"prereleases",
"package_types",
"keep_latest_packages",
"exclude_platforms",
"provenance",
)
model = python_models.PythonRemote
class PythonBlocklistEntrySerializer(core_serializers.ModelSerializer):
"""
Serializer for PythonBlocklistEntry.
The `repository` is supplied by the URL (not the request body) and is injected
by the viewset before saving.
"""
pulp_href = serializers.SerializerMethodField(
read_only=True,
help_text=_("The URL of this blocklist entry."),
)
repository = core_serializers.DetailRelatedField(
read_only=True,
view_name_pattern=r"repositories(-.*/.*)?-detail",
help_text=_("Repository this blocklist entry belongs to."),
)
name = serializers.CharField(
required=False,
allow_null=True,
default=None,
help_text=_(
"Package name to block (for all versions). Compared after PEP 503 normalization. "
"Required when 'filename' is not provided."
),
)
version = serializers.CharField(
required=False,
allow_null=True,
default=None,
help_text=_("Exact version string to block (e.g. '1.0'). Only used when 'name' is set."),
)
filename = serializers.CharField(
required=False,
allow_null=True,
default=None,
help_text=_("Exact filename to block. Required when 'name' is not provided."),
)
added_by = serializers.CharField(
read_only=True,
help_text=_("PRN of the user who added this blocklist entry."),
)
def get_pulp_href(self, obj):
repo_href = reverse("repositories-python/python-detail", kwargs={"pk": obj.repository_id})
return f"{repo_href}blocklist_entries/{obj.pk}/"
def validate(self, data):
"""
Validate that the blocklist entry is well-formed and not a duplicate.
"""
name = data.get("name")
filename = data.get("filename")
version = data.get("version")
if version and filename:
raise serializers.ValidationError(_("'version' cannot be used with 'filename'."))
if version and not name:
raise serializers.ValidationError(_("'version' requires 'name' to be provided."))
if bool(name) == bool(filename):
raise serializers.ValidationError(
_("Exactly one of 'name' or 'filename' must be provided.")
)
if version:
try:
Version(version)
except InvalidVersion:
raise serializers.ValidationError(
{"version": _("'{}' is not a valid version.").format(version)}
)
if name:
data["name"] = canonicalize_name(name)
name = data["name"]
repository = self.context.get("repository")
if repository:
qs = python_models.PythonBlocklistEntry.objects.filter(repository=repository)
if name and qs.filter(name=name, version=version).exists():
raise serializers.ValidationError(
_("A blocklist entry with this name and version already exists.")
)
if filename and qs.filter(filename=filename).exists():
raise serializers.ValidationError(
_("A blocklist entry with this filename already exists.")
)
data["repository"] = repository
return data
def create(self, validated_data):
"""
Create a new blocklist entry, recording the authenticated user in `added_by`.
"""
user = get_current_authenticated_user()
validated_data["added_by"] = get_prn(user) if user else ""
return super().create(validated_data)
class Meta:
fields = core_serializers.ModelSerializer.Meta.fields + (
"repository",
"name",
"version",
"filename",
"added_by",
)
model = python_models.PythonBlocklistEntry
class PythonBanderRemoteSerializer(serializers.Serializer):
"""
A Serializer for the initial step of creating a Python Remote from a Bandersnatch config file
"""
config = serializers.FileField(
help_text=_("A Bandersnatch config that may be used to construct a Python Remote."),
required=True,
write_only=True,
)
name = serializers.CharField(
help_text=_("A unique name for this remote"),
required=True,
)
policy = serializers.ChoiceField(
help_text=_(
"The policy to use when downloading content. The possible values include: "
"'immediate', 'on_demand', and 'streamed'. 'on_demand' is the default."
),
choices=core_models.Remote.POLICY_CHOICES,
default=core_models.Remote.ON_DEMAND,
)
class PythonPublicationSerializer(core_serializers.PublicationSerializer):
"""
A Serializer for PythonPublication.
"""
distributions = core_serializers.DetailRelatedField(
help_text=_(
"This publication is currently being hosted as configured by these distributions."
),
source="distribution_set",
view_name="pythondistributions-detail",
many=True,
read_only=True,
)
class Meta:
fields = core_serializers.PublicationSerializer.Meta.fields + ("distributions",)
model = python_models.PythonPublication