forked from pulp/pulp_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
683 lines (581 loc) · 25.2 KB
/
utils.py
File metadata and controls
683 lines (581 loc) · 25.2 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
import hashlib
import logging
import pkginfo
import re
import shutil
import tempfile
import zipfile
import json
from aiohttp.client_exceptions import ClientError
from collections import defaultdict
from datetime import timezone
from django.conf import settings
from django.db.utils import IntegrityError
from jinja2 import Template
from packaging.utils import canonicalize_name
from packaging.requirements import Requirement
from packaging.version import parse, InvalidVersion
from pypi_simple import ACCEPT_JSON_PREFERRED, ProjectPage
from pulpcore.plugin.models import Artifact, Remote
from pulpcore.plugin.exceptions import TimeoutException
from pulpcore.plugin.util import get_domain
log = logging.getLogger(__name__)
PYPI_LAST_SERIAL = "X-PYPI-LAST-SERIAL"
"""TODO This serial constant is temporary until Python repositories implements serials"""
PYPI_SERIAL_CONSTANT = 1000000000
SUPPORTED_METADATA_VERSIONS = ("1.0", "1.1", "1.2", "2.0", "2.1", "2.2", "2.3", "2.4")
SIMPLE_API_VERSION = "1.1"
PYPI_SIMPLE_V1_HTML = "application/vnd.pypi.simple.v1+html"
PYPI_SIMPLE_V1_JSON = "application/vnd.pypi.simple.v1+json"
simple_index_template = """<!DOCTYPE html>
<html>
<head>
<title>Simple Index</title>
<meta name="pypi:repository-version" content="{{ SIMPLE_API_VERSION }}">
</head>
<body>
{% for name, canonical_name in projects %}
<a href="{{ canonical_name }}/">{{ name }}</a><br/>
{% endfor %}
</body>
</html>
"""
# TODO in the future: data-yanked (not implemented yet because it is mutable)
simple_detail_template = """<!DOCTYPE html>
<html>
<head>
<title>Links for {{ project_name }}</title>
<meta name="pypi:repository-version" content="{{ SIMPLE_API_VERSION }}">
</head>
<body>
<h1>Links for {{ project_name }}</h1>
{%- for pkg in project_packages %}
<a href="{{ pkg.url }}#sha256={{ pkg.sha256 }}" rel="internal"
{%- if pkg.requires_python %} data-requires-python="{{ pkg.requires_python }}" {%- endif %}
{%- if pkg.metadata_sha256 %} data-dist-info-metadata="sha256={{ pkg.metadata_sha256 }}" data-core-metadata="sha256={{ pkg.metadata_sha256 }}"
{%- endif %} {% if pkg.provenance -%}
data-provenance="{{ pkg.provenance }}"{% endif %}>{{ pkg.filename }}</a><br/>
{%- endfor %}
</body>
</html>
""" # noqa: E501
DIST_EXTENSIONS = {
".whl": "bdist_wheel",
".exe": "bdist_wininst",
".egg": "bdist_egg",
".tar.bz2": "sdist",
".tar.gz": "sdist",
".zip": "sdist",
}
DIST_REGEXES = {
# regex from https://github.com/pypa/pip/blob/18.0/src/pip/_internal/wheel.py#L569
".whl": re.compile(
r"""^(?P<name>.+?)-(?P<version>.*?)
((-(?P<build>\d[^-]*?))?-(?P<pyver>.+?)-(?P<abi>.+?)-(?P<plat>.+?)
\.whl|\.dist-info)$""",
re.VERBOSE,
),
# regex based on https://setuptools.pypa.io/en/latest/deprecated/python_eggs.html#filename-embedded-metadata # noqa: E501
".egg": re.compile(
r"^(?P<name>.+?)-(?P<version>.*?)(-(?P<pyver>.+?(-(?P<plat>.+?))?))?\.egg|\.egg-info$"
), # noqa: E501
# regex based on https://github.com/python/cpython/blob/v3.7.0/Lib/distutils/command/bdist_wininst.py#L292 # noqa: E501
".exe": re.compile(r"^(?P<name>.+?)-(?P<version>.*?)\.(?P<plat>.+?)(-(?P<pyver>.+?))?\.exe$"),
}
DIST_TYPES = {
"bdist_wheel": pkginfo.Wheel,
"bdist_wininst": pkginfo.Distribution,
"bdist_egg": pkginfo.BDist,
"sdist": pkginfo.SDist,
}
def parse_project_metadata(project):
"""
Create a dictionary of python project metadata.
Args:
project (dict): Metadata relevant to the entire Python project
Returns:
dictionary: of python project metadata
"""
return {
# Core metadata
# Version 1.0
"author": project.get("author") or "",
"author_email": project.get("author_email") or "",
"description": project.get("description") or "",
"home_page": project.get("home_page") or "",
"keywords": project.get("keywords") or "",
"license": project.get("license") or "",
"metadata_version": project.get("metadata_version") or "",
"name": project.get("name") or "",
"platform": project.get("platform") or "",
"summary": project.get("summary") or "",
"version": project.get("version") or "",
# Version 1.1
"classifiers": json.dumps(project.get("classifiers", [])),
"download_url": project.get("download_url") or "",
"supported_platform": project.get("supported_platform") or "",
# Version 1.2
"maintainer": project.get("maintainer") or "",
"maintainer_email": project.get("maintainer_email") or "",
"obsoletes_dist": json.dumps(project.get("obsoletes_dist", [])),
"project_url": project.get("project_url") or "",
"project_urls": json.dumps(project.get("project_urls", {})),
"provides_dist": json.dumps(project.get("provides_dist", [])),
"requires_external": json.dumps(project.get("requires_external", [])),
"requires_dist": json.dumps(project.get("requires_dist", [])),
"requires_python": project.get("requires_python") or "",
# Version 2.1
"description_content_type": project.get("description_content_type") or "",
"provides_extras": json.dumps(project.get("provides_extras", [])),
# Version 2.2
"dynamic": json.dumps(project.get("dynamic", [])),
# Version 2.4
"license_expression": project.get("license_expression") or "",
"license_file": json.dumps(project.get("license_file", [])),
# Release metadata
"packagetype": project.get("packagetype") or "",
"python_version": project.get("python_version") or "",
"metadata_sha256": project.get("metadata_sha256"),
}
def parse_metadata(project, version, distribution):
"""
Extract metadata from a distribution.
Create a dictionary of metadata needed to create a PythonContentUnit from
the project, version, and distribution metadata.
Args:
project (dict): Metadata relevant to the entire Python project
version (string): Version of distribution
distribution (dict): Metadata of a single Python distribution
Returns:
dictionary: of useful python metadata
"""
package = parse_project_metadata(project)
package["filename"] = distribution.get("filename") or ""
package["packagetype"] = distribution.get("packagetype") or ""
package["version"] = version
package["url"] = distribution.get("url") or ""
package["sha256"] = distribution.get("digests", {}).get("sha256") or ""
package["python_version"] = distribution.get("python_version") or ""
package["requires_python"] = distribution.get("requires_python") or ""
package["size"] = distribution.get("size") or 0
return package
def get_project_metadata_from_file(filename):
"""
Gets the metadata of a Python Package.
Raises ValueError if filename has an unsupported extension
"""
extensions = list(DIST_EXTENSIONS.keys())
# Iterate through extensions since splitext does not support things like .tar.gz
# If no supported extension is found, ValueError is raised here
pkg_type_index = [filename.endswith(ext) for ext in extensions].index(True)
packagetype = DIST_EXTENSIONS[extensions[pkg_type_index]]
metadata = DIST_TYPES[packagetype](filename)
metadata.metadata_sha256 = compute_metadata_sha256(filename)
metadata.packagetype = packagetype
if packagetype == "sdist":
metadata.python_version = "source"
else:
pyver = ""
regex = DIST_REGEXES[extensions[pkg_type_index]]
if bdist_name := regex.match(filename):
pyver = bdist_name.group("pyver") or ""
metadata.python_version = pyver
return metadata
def extract_wheel_metadata(filename: str) -> bytes | None:
"""
Extract the metadata file content from a wheel file.
Returns the raw metadata content as bytes or None if metadata cannot be extracted.
"""
if not filename.endswith(".whl"):
return None
try:
with zipfile.ZipFile(filename, "r") as f:
metadata_paths = [p for p in f.namelist() if p.endswith("METADATA")]
sorted_paths = sorted(metadata_paths, key=lambda s: s.count("/"))
for metadata_path in sorted_paths:
file = f.read(metadata_path)
if b"Metadata-Version" in file:
return file
except (zipfile.BadZipFile, KeyError, OSError) as e:
log.warning(f"Failed to extract metadata file from {filename}: {e}")
return None
def compute_metadata_sha256(filename: str) -> str | None:
"""
Compute SHA256 hash of the metadata file from a Python package.
Returns SHA256 hash or None if metadata cannot be extracted.
"""
metadata_content = extract_wheel_metadata(filename)
return hashlib.sha256(metadata_content).hexdigest() if metadata_content else None
def artifact_to_python_content_data(filename, artifact, domain=None):
"""
Takes the artifact/filename and returns the metadata needed to create a PythonPackageContent.
"""
# Copy file to a temp directory under the user provided filename, we do this
# because pkginfo validates that the filename has a valid extension before
# reading it
with tempfile.NamedTemporaryFile("wb", dir=".", suffix=filename) as temp_file:
artifact.file.seek(0)
shutil.copyfileobj(artifact.file, temp_file)
temp_file.flush()
metadata = get_project_metadata_from_file(temp_file.name)
data = parse_project_metadata(vars(metadata))
data["sha256"] = artifact.sha256
data["size"] = artifact.size
data["filename"] = filename
data["pulp_domain"] = domain or artifact.pulp_domain
data["_pulp_domain"] = data["pulp_domain"]
return data
def artifact_to_metadata_artifact(
filename: str, artifact: Artifact, tmp_dir: str = "."
) -> Artifact | None:
"""
Creates artifact for metadata from the provided wheel artifact.
"""
if not filename.endswith(".whl"):
return None
with tempfile.NamedTemporaryFile("wb", dir=tmp_dir, suffix=filename, delete=False) as temp_file:
temp_wheel_path = temp_file.name
artifact.file.seek(0)
shutil.copyfileobj(artifact.file, temp_file)
temp_file.flush()
metadata_content = extract_wheel_metadata(temp_wheel_path)
if not metadata_content:
return None
with tempfile.NamedTemporaryFile(
"wb", dir=tmp_dir, suffix=".metadata", delete=False
) as temp_md:
temp_metadata_path = temp_md.name
temp_md.write(metadata_content)
temp_md.flush()
metadata_artifact = Artifact.init_and_validate(temp_metadata_path)
try:
metadata_artifact.save()
except IntegrityError:
metadata_artifact = Artifact.objects.get(
sha256=metadata_artifact.sha256, pulp_domain=get_domain()
)
return metadata_artifact
def fetch_json_release_metadata(name: str, version: str, remotes: set[Remote]) -> dict:
"""
Fetches metadata for a specific release from PyPI's JSON API. A release can contain
multiple distributions. See https://docs.pypi.org/api/json/#get-a-release for more details.
All remotes should have the same URL.
Returns:
Dict containing "info", "last_serial", "urls", and "vulnerabilities" keys.
Raises:
Exception if fetching from all remote URLs fails.
"""
remote = next(iter(remotes))
url = remote.get_remote_artifact_url(f"pypi/{name}/{version}/json")
result = None
for remote in remotes:
downloader = remote.get_downloader(url=url, max_retries=1)
try:
result = downloader.fetch()
break
except Exception:
continue
if result:
with open(result.path, "r") as file:
json_data = json.load(file)
return json_data
else:
raise Exception(f"Failed to fetch {url} from any remote.")
def python_content_to_json(base_path, content_query, version=None, domain=None):
"""
Converts a QuerySet of PythonPackageContent into the PyPi JSON format
https://www.python.org/dev/peps/pep-0566/
JSON metadata has:
info: Dict
last_serial: int
releases: Dict
urls: Dict
Returns None if version is specified but not found within content_query
"""
full_metadata = {"last_serial": 0} # For now the serial field isn't supported by Pulp
latest_content = latest_content_version(content_query, version)
if not latest_content:
return None
full_metadata.update({"info": python_content_to_info(latest_content[0])})
full_metadata.update({"releases": python_content_to_releases(content_query, base_path, domain)})
full_metadata.update({"urls": python_content_to_urls(latest_content, base_path, domain)})
return full_metadata
def latest_content_version(content_query, version):
"""
Walks through the content QuerySet and finds the instances that is the latest version.
If 'version' is specified, the function instead tries to find content instances
with that version and will return an empty list if nothing is found
"""
latest_version = version
latest_content = []
for content in content_query:
if version and parse(version) == parse(content.version):
latest_content.append(content)
elif not latest_version or parse(content.version) > parse(latest_version):
latest_content = [content]
latest_version = content.version
elif parse(content.version) == parse(latest_version):
latest_content.append(content)
return latest_content
def json_to_dict(data):
"""
Converts a JSON string into a Python dictionary.
Args:
data (string): JSON string
Returns:
dictionary: of JSON string
"""
if isinstance(data, dict):
return data
return json.loads(data)
def python_content_to_info(content):
"""
Takes in a PythonPackageContent instance and returns a dictionary of the Info fields
"""
return {
"name": content.name,
"version": content.version,
"summary": content.summary or "",
"keywords": content.keywords or "",
"description": content.description or "",
"description_content_type": content.description_content_type or "",
"bugtrack_url": None, # These two are basically never used
"docs_url": None,
"downloads": {"last_day": -1, "last_month": -1, "last_week": -1},
"download_url": content.download_url or "",
"home_page": content.home_page or "",
"author": content.author or "",
"author_email": content.author_email or "",
"maintainer": content.maintainer or "",
"maintainer_email": content.maintainer_email or "",
"license": content.license or "",
"requires_python": content.requires_python or None,
"package_url": content.project_url or "", # These two are usually identical
"project_url": content.project_url or "", # They also usually point to PyPI
"release_url": f"{content.project_url}{content.version}/" if content.project_url else "",
"project_urls": json_to_dict(content.project_urls) or None,
"platform": content.platform or "",
"requires_dist": json_to_dict(content.requires_dist) or None,
"classifiers": json_to_dict(content.classifiers) or None,
"yanked": False, # These are no longer used on PyPI, but are still present
"yanked_reason": None,
# New core metadata (Version 2.1, 2.2, 2.4)
"provides_extras": json_to_dict(content.provides_extras) or None,
"dynamic": json_to_dict(content.dynamic) or None,
"license_expression": content.license_expression or "",
"license_file": json_to_dict(content.license_file) or None,
}
def python_content_to_releases(content_query, base_path, domain=None):
"""
Takes a QuerySet of PythonPackageContent and returns a dictionary of releases
with each key being a version and value being a list of content for that version of the package
"""
releases = defaultdict(lambda: [])
for content in content_query:
releases[content.version].append(
python_content_to_download_info(content, base_path, domain)
)
return releases
def python_content_to_urls(contents, base_path, domain=None):
"""
Takes the latest content in contents and returns a list of download information
"""
return [python_content_to_download_info(content, base_path, domain) for content in contents]
def python_content_to_download_info(content, base_path, domain=None):
"""
Takes in a PythonPackageContent and base path of the distribution to create a dictionary of
download information for that content. This dictionary is used by Releases and Urls.
"""
def find_artifact():
_art = content_artifact.artifact
if not _art:
from pulpcore.plugin import models
_art = models.RemoteArtifact.objects.filter(content_artifact=content_artifact).first()
return _art
content_artifact = content.contentartifact_set.exclude(
relative_path__endswith=".metadata"
).first()
artifact = find_artifact()
origin = settings.CONTENT_ORIGIN or settings.PYPI_API_HOSTNAME or ""
origin = origin.strip("/")
prefix = settings.CONTENT_PATH_PREFIX.strip("/")
base_path = base_path.strip("/")
components = [origin, prefix, base_path, content.filename]
if domain:
components.insert(2, domain.name)
url = "/".join(components)
md5 = artifact.md5 if artifact and artifact.md5 else ""
return {
"comment_text": "",
"digests": {"md5": md5, "sha256": content.sha256},
"downloads": -1,
"filename": content.filename,
"has_sig": False,
"md5_digest": md5,
"packagetype": content.packagetype,
"python_version": content.python_version,
"requires_python": content.requires_python or None,
"size": content.size,
"upload_time": str(content.pulp_created),
"upload_time_iso_8601": str(content.pulp_created.isoformat()),
"url": url,
"yanked": False,
"yanked_reason": None,
}
def write_simple_index(project_names, streamed=False):
"""Writes the simple index."""
simple = Template(simple_index_template)
context = {
"SIMPLE_API_VERSION": SIMPLE_API_VERSION,
"projects": ((x, canonicalize_name(x)) for x in project_names),
}
return simple.stream(**context) if streamed else simple.render(**context)
def write_simple_detail(project_name, project_packages, streamed=False):
"""Writes the simple detail page of a package."""
detail = Template(simple_detail_template, autoescape=True)
context = {
"SIMPLE_API_VERSION": SIMPLE_API_VERSION,
"project_name": project_name,
"project_packages": project_packages,
}
return detail.stream(**context) if streamed else detail.render(**context)
def write_simple_index_json(project_names):
"""Writes the simple index in JSON format."""
return {
"meta": {"api-version": SIMPLE_API_VERSION, "_last-serial": PYPI_SERIAL_CONSTANT},
"projects": [
{"name": name, "_last-serial": PYPI_SERIAL_CONSTANT} for name in project_names
],
}
def write_simple_detail_json(project_name, project_packages):
"""Writes the simple detail page in JSON format."""
return {
"meta": {"api-version": SIMPLE_API_VERSION, "_last-serial": PYPI_SERIAL_CONSTANT},
"name": canonicalize_name(project_name),
"files": [
{
# v1.0, PEP 691
"filename": package["filename"],
"url": package["url"],
"hashes": {"sha256": package["sha256"]},
"requires-python": package["requires_python"] or None,
# data-dist-info-metadata is deprecated alias for core-metadata
"data-dist-info-metadata": (
{"sha256": package["metadata_sha256"]} if package["metadata_sha256"] else False
),
# PEP 714
"core-metadata": (
{"sha256": package["metadata_sha256"]} if package["metadata_sha256"] else False
),
# yanked and yanked_reason are not implemented because they are mutable
# (v1.1, PEP 700)
"size": package["size"],
"upload-time": format_upload_time(package["upload_time"]),
# (v1.3, PEP 740)
"provenance": package.get("provenance", None),
}
for package in project_packages
],
# (v1.1, PEP 700)
"versions": sorted(set(package["version"] for package in project_packages)),
# TODO in the future:
# alternate-locations (v1.2, PEP 708)
# project-status (v1.4, PEP 792 - pypi and docs differ)
}
def format_upload_time(upload_time):
"""Formats the upload time to be in Zulu time. UTC with Z suffix"""
if upload_time:
if upload_time.tzinfo:
dt = upload_time.astimezone(timezone.utc)
return dt.isoformat().replace("+00:00", "Z")
return None
class PackageIncludeFilter:
"""A special class to help filter Package's based on a remote's include/exclude"""
def __init__(self, remote):
self.remote = remote.cast()
self._filter_includes = self._parse_packages(self.remote.includes)
self._filter_excludes = self._parse_packages(self.remote.excludes)
def _parse_packages(self, packages):
config = defaultdict(lambda: defaultdict(list))
for value in packages:
requirement = Requirement(value)
requirement.name = canonicalize_name(requirement.name)
if requirement.specifier:
requirement.specifier.prereleases = True
config["range"][requirement.name].append(requirement)
else:
config["full"][requirement.name].append(requirement)
return config
def filter_project(self, project_name):
"""Return true/false if project_name would be allowed through remote's filters."""
project_name = canonicalize_name(project_name)
include_full = self._filter_includes.get("full", {})
include_range = self._filter_includes.get("range", {})
include = set(include_range.keys()).union(include_full.keys())
if include and project_name not in include:
return False
exclude_full = self._filter_excludes.get("full", {})
if project_name in exclude_full:
return False
return True
def filter_release(self, project_name, version):
"""Returns true/false if release would be allowed through remote's filters."""
project_name = canonicalize_name(project_name)
if not self.filter_project(project_name):
return False
try:
version = parse(version)
except (InvalidVersion, TypeError):
return False
include_range = self._filter_includes.get("range", {})
if project_name in include_range:
for req in include_range[project_name]:
if version in req.specifier:
break
else:
return False
exclude_range = self._filter_excludes.get("range", {})
if project_name in exclude_range:
for req in exclude_range[project_name]:
if version in req.specifier:
return False
return True
_remote_filters = {}
def get_remote_package_filter(remote):
if date_filter_tuple := _remote_filters.get(remote.pulp_id):
last_update, rfilter = date_filter_tuple
if last_update == remote.pulp_last_updated:
return rfilter
rfilter = PackageIncludeFilter(remote)
_remote_filters[remote.pulp_id] = (remote.pulp_last_updated, rfilter)
return rfilter
def get_remote_simple_page(package, remote, max_retries=1):
"""Gets the simple page for a package from a remote."""
url = remote.get_remote_artifact_url(f"simple/{package}/")
remote.headers = remote.headers or []
remote.headers.append({"Accept": ACCEPT_JSON_PREFERRED})
downloader = remote.get_downloader(url=url, max_retries=max_retries)
try:
d = downloader.fetch()
except (ClientError, TimeoutException):
return None
if d.headers["content-type"] == PYPI_SIMPLE_V1_JSON:
page = ProjectPage.from_json_data(json.load(open(d.path, "rb")), base_url=url)
else:
page = ProjectPage.from_html(package, open(d.path, "rb").read(), base_url=url)
return page
async def aget_remote_simple_page(package, remote, max_retries=1):
"""Gets the simple page for a package from a remote."""
url = remote.get_remote_artifact_url(f"simple/{package}/")
remote.headers = remote.headers or []
remote.headers.append({"Accept": ACCEPT_JSON_PREFERRED})
downloader = remote.get_downloader(url=url, max_retries=max_retries)
try:
d = await downloader.run()
except (ClientError, TimeoutException):
return None
if d.headers["content-type"] == PYPI_SIMPLE_V1_JSON:
page = ProjectPage.from_json_data(json.load(open(d.path, "rb")), base_url=url)
else:
page = ProjectPage.from_html(package, open(d.path, "rb").read(), base_url=url)
return page