-
-
Notifications
You must be signed in to change notification settings - Fork 778
Replace deprecated jsonschema.RefResolver
with referencing.Registry
#2023
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
Open
radoering
wants to merge
1
commit into
spec-first:main
Choose a base branch
from
radoering:fix-jsonschema-refresolver-deprecation
base: main
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 hidden or 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 |
---|---|---|
|
@@ -4,6 +4,7 @@ | |
|
||
import contextlib | ||
import io | ||
import json | ||
import os | ||
import typing as t | ||
import urllib.parse | ||
|
@@ -13,9 +14,11 @@ | |
|
||
import requests | ||
import yaml | ||
from jsonschema import Draft4Validator, RefResolver | ||
from jsonschema.exceptions import RefResolutionError, ValidationError # noqa | ||
from jsonschema import Draft4Validator | ||
from jsonschema.exceptions import ValidationError | ||
from jsonschema.validators import extend | ||
from referencing import Registry, Resource | ||
from referencing.jsonschema import DRAFT4 | ||
|
||
from .utils import deep_get | ||
|
||
|
@@ -62,12 +65,27 @@ def __call__(self, uri): | |
return yaml.load(fh, ExtendedSafeLoader) | ||
|
||
|
||
handlers = { | ||
"http": URLHandler(), | ||
"https": URLHandler(), | ||
"file": FileHandler(), | ||
"": FileHandler(), | ||
} | ||
def resource_from_spec(spec: t.Dict[str, t.Any]) -> Resource: | ||
"""Create a `referencing.Resource` from a schema specification.""" | ||
return Resource.from_contents(spec, default_specification=DRAFT4) | ||
|
||
|
||
def retrieve(uri: str) -> Resource: | ||
"""Retrieve a resource from a URI. | ||
|
||
This function is passed to the `referencing.Registry`, | ||
which calls it any URI is not present in the registry is accessed.""" | ||
parsed = urllib.parse.urlsplit(uri) | ||
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. Would you please consider adding pydoc for this new function? 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. Done. |
||
if parsed.scheme in ("http", "https"): | ||
content = URLHandler()(uri) | ||
elif parsed.scheme in ("file", ""): | ||
content = FileHandler()(uri) | ||
else: # pragma: no cover | ||
# Default branch from jsonschema.RefResolver.resolve_remote() | ||
# for backwards compatibility. | ||
with urllib.request.urlopen(uri) as url: | ||
content = json.loads(url.read().decode("utf-8")) | ||
return resource_from_spec(content) | ||
|
||
|
||
def resolve_refs(spec, store=None, base_uri=""): | ||
|
@@ -78,32 +96,37 @@ def resolve_refs(spec, store=None, base_uri=""): | |
""" | ||
spec = deepcopy(spec) | ||
store = store or {} | ||
resolver = RefResolver(base_uri, spec, store, handlers=handlers) | ||
registry = Registry(retrieve=retrieve).with_resources( | ||
( | ||
(base_uri, resource_from_spec(spec)), | ||
*((key, resource_from_spec(value)) for key, value in store.items()), | ||
) | ||
) | ||
|
||
def _do_resolve(node): | ||
def _do_resolve(node, resolver): | ||
if isinstance(node, Mapping) and "$ref" in node: | ||
path = node["$ref"][2:].split("/") | ||
try: | ||
# resolve known references | ||
retrieved = deep_get(spec, path) | ||
node.update(retrieved) | ||
if isinstance(retrieved, Mapping) and "$ref" in retrieved: | ||
node = _do_resolve(node) | ||
node = _do_resolve(node, resolver) | ||
node.pop("$ref", None) | ||
return node | ||
except KeyError: | ||
# resolve external references | ||
with resolver.resolving(node["$ref"]) as resolved: | ||
return _do_resolve(resolved) | ||
resolved = resolver.lookup(node["$ref"]) | ||
return _do_resolve(resolved.contents, resolved.resolver) | ||
elif isinstance(node, Mapping): | ||
for k, v in node.items(): | ||
node[k] = _do_resolve(v) | ||
node[k] = _do_resolve(v, resolver) | ||
elif isinstance(node, (list, tuple)): | ||
for i, _ in enumerate(node): | ||
node[i] = _do_resolve(node[i]) | ||
node[i] = _do_resolve(node[i], resolver) | ||
return node | ||
|
||
res = _do_resolve(spec) | ||
res = _do_resolve(spec, registry.resolver(base_uri)) | ||
return res | ||
|
||
|
||
|
This file contains hidden or 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 hidden or 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.
I think the imports are grouped (1) python standard, (2) third party and (3) connexion. FWIW maybe it's worth sorting within categories (1) and (2) here?
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.
There is a sorting within categories: At first normal
imports
sorted alphabetically, thenfrom
imports sorted alphabetically.If I change the order
isort
will complain.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.
Thanks for explaining, I didn't spot that pattern, never mind!