-
Notifications
You must be signed in to change notification settings - Fork 9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Proof-of-concept for using simple-repository instead of the non-standards based JSON API #10
Open
pelson
wants to merge
1
commit into
astrofrog:master
Choose a base branch
from
pelson:feature/use-simple-repository
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
from .core import main | ||
|
||
|
||
if __name__ == '__main__': | ||
from pypi_timemachine.core import main | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,37 +1,97 @@ | ||
import socket | ||
from contextlib import asynccontextmanager | ||
import dataclasses | ||
from datetime import datetime | ||
import socket | ||
import sys | ||
import typing | ||
|
||
import click | ||
import requests | ||
import fastapi | ||
import httpx | ||
from simple_repository.components.core import RepositoryContainer, SimpleRepository | ||
from simple_repository.components.http import HttpRepository | ||
from simple_repository_server.routers import simple | ||
from simple_repository import model | ||
import uvicorn | ||
|
||
|
||
if sys.version_info >= (3, 12): | ||
from typing import override | ||
else: | ||
override = lambda fn: fn | ||
|
||
from tornado.ioloop import IOLoop | ||
from tornado.web import RequestHandler, Application | ||
from tornado.routing import PathMatches | ||
|
||
MAIN_PYPI = 'https://pypi.org/simple/' | ||
JSON_URL = 'https://pypi.org/pypi/{package}/json' | ||
|
||
PACKAGE_HTML = """ | ||
<!DOCTYPE html> | ||
<html> | ||
<head> | ||
<title>Links for {package}</title> | ||
</head> | ||
<body> | ||
<h1>Links for {package}</h1> | ||
{links} | ||
</body> | ||
</html> | ||
""" | ||
|
||
|
||
def parse_iso(dt): | ||
|
||
|
||
def parse_iso(dt) -> datetime: | ||
try: | ||
return datetime.strptime(dt, '%Y-%m-%d') | ||
except: | ||
return datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S') | ||
|
||
|
||
def create_app(repo: SimpleRepository) -> fastapi.FastAPI: | ||
@asynccontextmanager | ||
async def lifespan(app: fastapi.FastAPI) -> typing.AsyncIterator[None]: | ||
async with httpx.AsyncClient() as http_client: | ||
app.include_router(simple.build_router(repo, http_client), prefix="") | ||
yield | ||
|
||
app = fastapi.FastAPI( | ||
openapi_url=None, # Disables automatic OpenAPI documentation (Swagger & Redoc) | ||
lifespan=lifespan, | ||
) | ||
return app | ||
|
||
|
||
class DateFilteredReleases(RepositoryContainer): | ||
""" | ||
A component used to remove released projects from the source | ||
repository if they were released after the configured date. | ||
|
||
This component can be used only if the source repository exposes the upload | ||
date according to PEP-700: https://peps.python.org/pep-0700/. | ||
|
||
""" | ||
def __init__( | ||
self, | ||
source: SimpleRepository, | ||
cutoff_date: datetime, | ||
) -> None: | ||
self._cutoff_date = cutoff_date | ||
super().__init__(source) | ||
|
||
@override | ||
async def get_project_page( | ||
self, | ||
project_name: str, | ||
*, | ||
request_context: model.RequestContext = model.RequestContext.DEFAULT, | ||
) -> model.ProjectDetail: | ||
project_page = await super().get_project_page( | ||
project_name, | ||
request_context=request_context, | ||
) | ||
|
||
return self._exclude_recent_distributions( | ||
project_page=project_page, | ||
now=datetime.now(), | ||
) | ||
|
||
def _exclude_recent_distributions( | ||
self, | ||
project_page: model.ProjectDetail, | ||
now: datetime, | ||
) -> model.ProjectDetail: | ||
filtered_files = tuple( | ||
file for file in project_page.files | ||
if not file.upload_time or | ||
(file.upload_time <= self._cutoff_date) | ||
) | ||
return dataclasses.replace(project_page, files=filtered_files) | ||
|
||
|
||
@click.command() | ||
@click.argument('cutoff_date') | ||
@click.option('--port', default=None) | ||
|
@@ -40,43 +100,20 @@ def main(cutoff_date, port, quiet): | |
|
||
CUTOFF = parse_iso(cutoff_date) | ||
|
||
INDEX = requests.get(MAIN_PYPI).content | ||
repo = DateFilteredReleases( | ||
HttpRepository(MAIN_PYPI), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Forgot to say: There is no real reason not to parameterise this now... it is something that has been asked for to support private indexes. (e.g. https://www.reddit.com/r/Python/comments/1cte019/comment/l4bh02p/ #8) |
||
cutoff_date=CUTOFF, | ||
) | ||
|
||
class MainIndexHandler(RequestHandler): | ||
|
||
async def get(self): | ||
return self.write(INDEX) | ||
|
||
class PackageIndexHandler(RequestHandler): | ||
|
||
async def get(self, package): | ||
|
||
package_index = requests.get(JSON_URL.format(package=package)).json() | ||
release_links = "" | ||
for release in package_index['releases'].values(): | ||
for file in release: | ||
release_date = parse_iso(file['upload_time']) | ||
if release_date < CUTOFF: | ||
if file['requires_python'] is None: | ||
release_links += ' <a href="{url}#sha256={sha256}">{filename}</a><br/>\n'.format(url=file['url'], sha256=file['digests']['sha256'], filename=file['filename']) | ||
else: | ||
rp = file['requires_python'].replace('>', '>') | ||
release_links += ' <a href="{url}#sha256={sha256}" data-requires-python="{rp}">{filename}</a><br/>\n'.format(url=file['url'], sha256=file['digests']['sha256'], rp=rp, filename=file['filename']) | ||
|
||
self.write(PACKAGE_HTML.format(package=package, links=release_links)) | ||
app = create_app(repo) | ||
|
||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | ||
sock.bind(('localhost', 0)) | ||
if port is None: | ||
port = sock.getsockname()[1] | ||
sock.close() | ||
|
||
app = Application([(r"/", MainIndexHandler), | ||
(PathMatches(r"/(?P<package>\S+)\//?"), PackageIndexHandler)]) | ||
|
||
app.listen(port=port) | ||
|
||
if not quiet: | ||
print(f'Starting pypi-timemachine server at http://localhost:{port}') | ||
|
||
IOLoop.instance().start() | ||
uvicorn.run(app=app, port=int(port)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also caused by some inflexibility on
simple-repository-server
(at https://github.com/simple-repository/simple-repository-server/blob/main/simple_repository_server/routers/simple.py#L41).There is no good reason for this limitation, but it would require some more thought than I have capacity for this evening 😴