-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
9 changed files
with
653 additions
and
0 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,180 @@ | ||
# Created by https://www.toptal.com/developers/gitignore/api/python | ||
# Edit at https://www.toptal.com/developers/gitignore?templates=python | ||
\#* | ||
|
||
scratch.py | ||
notes.org | ||
|
||
### Python ### | ||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
*$py.class | ||
|
||
# C extensions | ||
*.so | ||
|
||
# Distribution / packaging | ||
.Python | ||
build/ | ||
develop-eggs/ | ||
dist/ | ||
downloads/ | ||
eggs/ | ||
.eggs/ | ||
lib/ | ||
lib64/ | ||
parts/ | ||
sdist/ | ||
var/ | ||
wheels/ | ||
share/python-wheels/ | ||
*.egg-info/ | ||
.installed.cfg | ||
*.egg | ||
MANIFEST | ||
|
||
# PyInstaller | ||
# Usually these files are written by a python script from a template | ||
# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
*.manifest | ||
*.spec | ||
|
||
# Installer logs | ||
pip-log.txt | ||
pip-delete-this-directory.txt | ||
|
||
# Unit test / coverage reports | ||
htmlcov/ | ||
.tox/ | ||
.nox/ | ||
.coverage | ||
.coverage.* | ||
.cache | ||
nosetests.xml | ||
coverage.xml | ||
*.cover | ||
*.py,cover | ||
.hypothesis/ | ||
.pytest_cache/ | ||
cover/ | ||
|
||
# Translations | ||
*.mo | ||
*.pot | ||
|
||
# Django stuff: | ||
*.log | ||
local_settings.py | ||
db.sqlite3 | ||
db.sqlite3-journal | ||
|
||
# Flask stuff: | ||
instance/ | ||
.webassets-cache | ||
|
||
# Scrapy stuff: | ||
.scrapy | ||
|
||
# Sphinx documentation | ||
docs/_build/ | ||
|
||
# PyBuilder | ||
.pybuilder/ | ||
target/ | ||
|
||
# Jupyter Notebook | ||
.ipynb_checkpoints | ||
|
||
# IPython | ||
profile_default/ | ||
ipython_config.py | ||
|
||
# pyenv | ||
# For a library or package, you might want to ignore these files since the code is | ||
# intended to run in multiple environments; otherwise, check them in: | ||
# .python-version | ||
|
||
# pipenv | ||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. | ||
# However, in case of collaboration, if having platform-specific dependencies or dependencies | ||
# having no cross-platform support, pipenv may install dependencies that don't work, or not | ||
# install all needed dependencies. | ||
#Pipfile.lock | ||
|
||
# poetry | ||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. | ||
# This is especially recommended for binary packages to ensure reproducibility, and is more | ||
# commonly ignored for libraries. | ||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control | ||
#poetry.lock | ||
|
||
# pdm | ||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. | ||
#pdm.lock | ||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it | ||
# in version control. | ||
# https://pdm.fming.dev/#use-with-ide | ||
.pdm.toml | ||
|
||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm | ||
__pypackages__/ | ||
|
||
# Celery stuff | ||
celerybeat-schedule | ||
celerybeat.pid | ||
|
||
# SageMath parsed files | ||
*.sage.py | ||
|
||
# Environments | ||
.env | ||
.venv | ||
env/ | ||
venv/ | ||
ENV/ | ||
env.bak/ | ||
venv.bak/ | ||
|
||
# Spyder project settings | ||
.spyderproject | ||
.spyproject | ||
|
||
# Rope project settings | ||
.ropeproject | ||
|
||
# mkdocs documentation | ||
/site | ||
|
||
# mypy | ||
.mypy_cache/ | ||
.dmypy.json | ||
dmypy.json | ||
|
||
# Pyre type checker | ||
.pyre/ | ||
|
||
# pytype static type analyzer | ||
.pytype/ | ||
|
||
# Cython debug symbols | ||
cython_debug/ | ||
|
||
# PyCharm | ||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can | ||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore | ||
# and can be added to the global gitignore or merged into this file. For a more nuclear | ||
# option (not recommended) you can uncomment the following to ignore the entire idea folder. | ||
#.idea/ | ||
|
||
### Python Patch ### | ||
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration | ||
poetry.toml | ||
|
||
# ruff | ||
.ruff_cache/ | ||
|
||
# LSP config files | ||
pyrightconfig.json | ||
|
||
# End of https://www.toptal.com/developers/gitignore/api/python |
Large diffs are not rendered by default.
Oops, something went wrong.
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 |
---|---|---|
@@ -0,0 +1,28 @@ | ||
[tool.poetry] | ||
name = "sparql-fastapi" | ||
version = "0.1.0" | ||
description = "" | ||
authors = ["Your Name <[email protected]>"] | ||
readme = "README.md" | ||
|
||
[tool.poetry.dependencies] | ||
python = "^3.12" | ||
sparqlwrapper = "^2.0.0" | ||
toolz = "^0.12.1" | ||
pydantic = "^2.8.2" | ||
|
||
|
||
[tool.poetry.group.dev.dependencies] | ||
ruff = "^0.5.4" | ||
deptry = "^0.17.0" | ||
|
||
[build-system] | ||
requires = ["poetry-core"] | ||
build-backend = "poetry.core.masonry.api" | ||
|
||
|
||
[tool.ruff] | ||
lint.ignore = ["F401"] | ||
|
||
[tool.deptry.package_module_name_map] | ||
sparqlwrapper = "SPARQLWrapper" |
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 |
---|---|---|
@@ -0,0 +1 @@ | ||
from sparql_fastapi.adapter import SPARQLModelAdapter |
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 |
---|---|---|
@@ -0,0 +1,43 @@ | ||
"""SPARQLModelAdapter class for QueryResult to Pydantic model conversions.""" | ||
|
||
from collections.abc import Sequence | ||
|
||
from SPARQLWrapper import JSON, QueryResult, SPARQLWrapper | ||
from pydantic import BaseModel | ||
from sparql_fastapi.utils._types import _TModelConstructorCallable | ||
from sparql_fastapi.utils.utils import ( | ||
get_bindings_from_query_result, | ||
instantiate_model_from_kwargs, | ||
) | ||
|
||
|
||
class SPARQLModelAdapter[ModelType: BaseModel]: | ||
"""Adapter/Mapper for QueryResult to Pydantic model conversions.""" | ||
|
||
def __init__(self, sparql_wrapper: SPARQLWrapper) -> None: | ||
self.sparql_wrapper = sparql_wrapper | ||
|
||
if self.sparql_wrapper.returnFormat != "json": | ||
self.sparql_wrapper.setReturnFormat(JSON) | ||
|
||
def __call__(self, query: str, model_constructor) -> Sequence[ModelType]: | ||
self.sparql_wrapper.setQuery(query) | ||
query_result: QueryResult = self.sparql_wrapper.query() | ||
|
||
if isinstance(model_constructor, type(BaseModel)): | ||
bindings = get_bindings_from_query_result(query_result) | ||
models: list[ModelType] = [ | ||
instantiate_model_from_kwargs(model_constructor, **binding) | ||
for binding in bindings | ||
] | ||
|
||
elif isinstance(model_constructor, _TModelConstructorCallable): | ||
models: list[ModelType] = model_constructor(query_result) | ||
|
||
else: | ||
raise TypeError( | ||
"Argument 'model_constructor' must be a model class " | ||
"or a model constructor callable." | ||
) | ||
|
||
return models |
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 |
---|---|---|
@@ -0,0 +1,17 @@ | ||
"""Type definitions for sparql_fastapi.""" | ||
|
||
from typing import Annotated, Protocol, TypeVar, runtime_checkable | ||
|
||
from pydantic import BaseModel | ||
|
||
|
||
_TModelInstance: Annotated[TypeVar, "Type defintion for Pydantic model instances."] = ( | ||
TypeVar("_TModelInstance", bound=BaseModel) | ||
) | ||
|
||
|
||
@runtime_checkable | ||
class _TModelConstructorCallable[ModelType: BaseModel](Protocol): | ||
"""Callback protocol for model constructor callables.""" | ||
|
||
def __call__(self, **kwargs) -> ModelType: ... |
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 |
---|---|---|
@@ -0,0 +1,66 @@ | ||
"""SPARQL/FastAPI utils.""" | ||
|
||
from collections.abc import Iterator, Mapping | ||
from typing import cast | ||
|
||
from SPARQLWrapper import QueryResult | ||
from pydantic import BaseModel | ||
from toolz import valmap | ||
|
||
|
||
def get_bindings_from_query_result(query_result: QueryResult) -> Iterator[dict]: | ||
"""Extract just the bindings from a SPARQLWrapper.QueryResult.""" | ||
query_json = cast(Mapping, query_result.convert()) | ||
bindings = map( | ||
lambda binding: valmap(lambda v: v["value"], binding), | ||
query_json["results"]["bindings"], | ||
) | ||
|
||
return bindings | ||
|
||
|
||
def instantiate_model_from_kwargs[ModelType: BaseModel]( | ||
model: type[ModelType], **kwargs | ||
) -> ModelType: | ||
"""Instantiate a (potentially nested) model from (flat) kwargs. | ||
Example: | ||
class SimpleModel(BaseModel): | ||
x: int | ||
y: int | ||
class NestedModel(BaseModel): | ||
a: str | ||
b: SimpleModel | ||
class ComplexModel(BaseModel): | ||
p: str | ||
q: NestedModel | ||
model = instantiate_model_from_kwargs(ComplexModel, x=1, y=2, a="a value", p="p value") | ||
print(model) # p='p value' q=NestedModel(a='a value', b=SimpleModel(x=1, y=2)) | ||
""" | ||
|
||
def _get_bindings(model: type[ModelType], **kwargs) -> dict: | ||
"""Get the bindings needed for model instantation. | ||
The function traverses model.model_fields | ||
and constructs a bindings dict by either getting values from kwargs or field defaults. | ||
For model fields the recursive clause runs. | ||
Note: This needs exception handling and proper testing. | ||
""" | ||
return { | ||
k: ( | ||
v.annotation(**_get_bindings(v.annotation, **kwargs)) | ||
if isinstance(v.annotation, type(BaseModel)) | ||
else kwargs.get(k, v.default) | ||
) | ||
for k, v in model.model_fields.items() | ||
} | ||
|
||
return model(**_get_bindings(model, **kwargs)) |
Empty file.