Skip to content

[RFC]validators: add yaml parsing based on suffix #754

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions jsonschema/tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -1793,6 +1793,8 @@ def get(self, url):
class _ReallyFakeJSONResponse(object):

_response = attr.ib()
text = str(_response)

def json(self):
return json.loads(self._response)

25 changes: 18 additions & 7 deletions jsonschema/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -837,18 +837,29 @@ def resolve_remote(self, uri):
except ImportError:
requests = None

try:
import yaml
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be delayed even later so we don't add overhead if yaml is not being used?

Perhaps json importing could do the same and save some startup time.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not think this is needed. A failed import is very fast, and even a successful one.

except ImportError:
yaml = None

scheme = urlsplit(uri).scheme

if scheme in self.handlers:
result = self.handlers[scheme](uri)
elif scheme in [u"http", u"https"] and requests:
# Requests has support for detecting the correct encoding of
# json over http
result = requests.get(uri).json()
else:
# Otherwise, pass off to urllib and assume utf-8
with urlopen(uri) as url:
result = json.loads(url.read().decode("utf-8"))
path = urlsplit(uri).path
if scheme in [u"http", u"https"] and requests:
# Requests has support for detecting the correct encoding
received = requests.get(uri).text
else:
# Otherwise, pass off to urllib and assume utf-8
with urlopen(uri) as url:
received = url.read().decode("utf-8")

if path.endswith((".yaml", ".yml")) and yaml:
result = yaml.safe_load(received)
else:
result = json.loads(received)

if self.cache_remote:
self.store[uri] = result
Expand Down