Skip to content

Commit

Permalink
✨ Add an API call for downloading the source of a PEP
Browse files Browse the repository at this point in the history
  • Loading branch information
davep committed Jan 28, 2025
1 parent 783785f commit bef0dd1
Showing 1 changed file with 61 additions and 10 deletions.
71 changes: 61 additions & 10 deletions src/peplum/peps/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

##############################################################################
# HTTPX imports.
from httpx import AsyncClient, HTTPStatusError, RequestError
from httpx import AsyncClient, HTTPStatusError, RequestError, Response


##############################################################################
Expand Down Expand Up @@ -38,19 +38,20 @@ def _client(self) -> AsyncClient:
self._client_ = AsyncClient()
return self._client_

async def get_peps(self) -> dict[int, dict[str, Any]]:
"""Download a fresh list of all known PEPs.
async def _get(self, url: str) -> Response:
"""Make a GET request.
Args:
url: The URL to make the request of.
Returns:
The PEP JSON data.
The response.
Raises:
RequestError: If there was a problem getting the PEPS.
RequestError: If there was some sort of error.
"""
try:
response = await self._client.get(
self._URL, headers={"user-agent": self.AGENT}
)
response = await self._client.get(url, headers={"user-agent": self.AGENT})
except (RequestError, SSLCertVerificationError) as error:
raise self.RequestError(str(error)) from None

Expand All @@ -59,10 +60,60 @@ async def get_peps(self) -> dict[int, dict[str, Any]]:
except HTTPStatusError as error:
raise self.RequestError(str(error)) from None

if isinstance(raw_data := response.json(), dict):
return raw_data
return response

async def get_peps(self) -> dict[int, dict[str, Any]]:
"""Download a fresh list of all known PEPs.
Returns:
The PEP JSON data.
Raises:
RequestError: If there was a problem getting the PEPS.
"""
if isinstance(
raw_data := (
await self._get("https://peps.python.org/api/peps.json")
).json(),
dict,
):
return raw_data
raise RequestError("Unexpected data received from the PEP API")

@staticmethod
def pep_file(pep: int) -> str:
"""Generate the name of the source file of a PEP.
Args:
pep: The number of the PEP.
Returns:
The name of the source file for that PEP.
"""
return f"pep-{pep:04}.rst"

@classmethod
def pep_url(cls, pep: int) -> str:
"""Generate the URL for the source of a PEP.
Args:
pep: The number of the PEP.
Returns:
The URL for the source of the PEP.
"""
return f"https://raw.githubusercontent.com/python/peps/refs/heads/main/peps/{cls.pep_file(pep)}"

async def get_pep(self, pep: int) -> str:
"""Download the text of a given PEP.
Args:
pep: The number of the PEP to download.
Returns:
The text for the PEP.
"""
return (await self._get(self.pep_url(pep))).text


### api.py ends here

0 comments on commit bef0dd1

Please sign in to comment.