Skip to content

Instantly share code, notes, and snippets.

@sethmlarson
Created November 13, 2023 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sethmlarson/852341a9b7899eda7d22d8c362c0a095 to your computer and use it in GitHub Desktop.
Save sethmlarson/852341a9b7899eda7d22d8c362c0a095 to your computer and use it in GitHub Desktop.
Simple module for querying data from py-code.org
# MIT License
#
# Copyright (c) 2023 Seth Michael Larson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Simple module for querying data from py-code.org"""
import hashlib
import typing
from pathlib import Path
import duckdb
import urllib3
__all__ = ["query", "get_path", "get_data"]
def query(q: str, /) -> typing.Generator[None, None, None]:
"""Run a query in DuckDB and iterate over the results as tuples"""
results = duckdb.query(q.strip())
while batch := results.fetchmany(1000):
yield from batch
def get_path(repository: str, project_name: str, path: str) -> Path:
"""Returns the filepath of a local copy of a remote file"""
cache_key = Path(
# :200 is used to protect against "filename too long" errors.
f"cache/{project_name}/{repository}-{path.replace('/', '-')[:200]}-{hashlib.md5(path.encode()).hexdigest()[:8]}"
)
if not cache_key.exists():
cache_key.parent.mkdir(parents=True, exist_ok=True)
mirror_url = f"https://raw.githubusercontent.com/pypi-data/pypi-mirror-{repository}/code/{path}"
resp = None
try:
resp = urllib3.request(
"GET",
mirror_url,
headers={"Accept-Encoding": "gzip"},
preload_content=False,
)
if resp.status != 200:
raise ValueError(
f"Could not find file for repository={repository}, project_name={project_name}, "
f"path={path}. Are you checking WHERE skip_reason != '' in query?"
)
with cache_key.open(mode="wb") as f:
while chunk := resp.read(100 * 1024 * 1024):
f.write(chunk)
# If anything fails we want to make sure the cache entry gets removed.
except BaseException:
cache_key.unlink(missing_ok=True)
raise
# Always close out our connection.
finally:
if resp is not None:
resp.close()
return cache_key
def get_data(repository: str, project_name: str, path: str) -> bytes:
"""Fetches data from a file"""
return get_path(repository, project_name, path).open(mode="rb").read()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment