Comments (4)
Thanks for the response @Julian! This suggestions is basically when I'm doing now as a workaround. The downside is that users of the custom validator must know what registry to use with it's meta validator if they want to check it. Of course since I'm both the user and creator that's doable, as you suggest.
Also I missed that check_schema is a class method, thanks for pointing that out!
I understand the points about general overhauls based on vocabularies, so I think I agree this doesn't warrant a change now since there is a relatively simple work around.
Thanks for the discussion!
from jsonschema.
Thanks for the detailed issue! I haven't read it carefully yet but skimming it certainly seems to make sense. Will probably be a few days (even not including the weekend) before I look, but just ACKing that I saw it.
from jsonschema.
Hey @Julian, don't want to bother too much but let me know if you've had a chance to take a look at this!
from jsonschema.
So here's a self contained example, just because I tidied it slightly as I was reading your comment:
meta_schema = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:meta.schema.json",
"$vocabulary": {
"https://json-schema.org/draft/2020-12/vocab/core": True,
"https://json-schema.org/draft/2020-12/vocab/applicator": True,
"https://json-schema.org/draft/2020-12/vocab/validation": True,
"https://json-schema.org/draft/2020-12/vocab/meta-data": True,
"https://json-schema.org/draft/2020-12/vocab/format-annotation": True,
"https://json-schema.org/draft/2020-12/vocab/content": True,
"https://json-schema.org/draft/2020-12/vocab/unevaluated": True
},
"allOf": [
{ "$ref": "https://json-schema.org/draft/2020-12/schema" },
{ "$ref": "urn:vocab.schema.json" }
]
}
vocab = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:vocab.schema.json",
"title": "Meta schema for my vocab",
"properties": {
"mykeyword": { "type": "string" }
}
}
schema = {
"$schema": "urn:meta.schema.json",
"mykeyword": "this is a test"
}
from jsonschema import exceptions, validators
from referencing import Registry, Resource
import json
import jsonschema
def my_callable(validator, value, instance, schema):
if instance == 37:
yield exceptions.ValidationError("NO!")
def get_validator():
MyValidator = validators.extend(
validators.Draft202012Validator,
validators={"mykeyword": my_callable},
)
MyValidator.META_SCHEMA = meta_schema
return validators.validates(meta_schema["$id"])(MyValidator)
# Set up the jsonschema validator to load local files
registry = Resource.from_contents(vocab) @ Registry()
MyValidator = get_validator()
This is because check_schema creates a new Validator with no option to pass a registry here. To be honest, I also don't understand why a new validator is created rather than using self (or cls in this case).
It's a classmethod, it indeed doesn't create a new Validator and does exactly use cls
, you don't call it on an instance!
That it's a classmethod is documented at the bottom here or in the API documentation, but if there's some other place you looked and didn't find that let me know.
To now jump directly to answering how you can provide a registry, you can simply create a validator instance for the meta schema if you'd like, and then pass it whatever you want (a registry) i.e.:
MetaschemaValidator = validators.validator_for(MyValidator.META_SCHEMA) # or directly use Draft202012Validator
meta_schema_validator = MetaschemaValidator(MyValidator.META_SCHEMA, registry=registry)
print("valid schema:", meta_schema_validator.is_valid(schema))
print("invalid schema:", meta_schema_validator.is_valid({"mykeyword": 37}))
validator = MyValidator(schema, registry=registry)
print("valid instace:", validator.is_valid(73))
print("invalid instace:", validator.is_valid(37))
Yes check_schema
could take all the arguments that a Validator
does, and if it were written today it probably would, but there are a few small reasons not to add it right now:
check_schema
likely needs deprecating, because there is a difference between "what schemas are valid under a metaschema" and "what schemas are valid at all under a dialect" -- this library and that function predate a lot of modern JSON Schema complexity, and always really did the first part there, mostly because it wasn't clear what to do for the second part (schemas which are invalid but the metaschema doesn't deem them so). But that indeed is a thing, and the spec now simply says "well call them invalid" more or less. Rather than makingcheck_schema
be that though, which would potentially be a surprising change, it probably needs to be a new function.- secondly, in brief, the whole validator interface is due for a refresh for similar reasons -- newer versions of JSON Schema have made making validators lots more complicated (by introducing the vocabulary system, which is still under development in the spec) -- if/when it stabilizes, some interface which better supports vocabularies will be introduced (right now there essentially is no representation of a vocabulary in this library, just a dialect). And when that happens, the
Validator
protocol will likely change. (Even worse is that in theory one can have a validator whose metaschema isn't something the library knows how to validate, because it's written in some dialect that we don't know about.)
The 2 above things basically mean I don't really want to make tweaks that aren't completely necessary (like the referencing changes in the last few versions) -- and since what you're doing is easily doable using existing means (creating a normal validator with your meta schema) I'm inclined to say "just use that for now" I think rather than changing it too much.
Let me know if the above makes sense / helps you get what you're after.
from jsonschema.
Related Issues (20)
- jsonschema.TypeChecker with additional types fails to work after several reference resolutions by the referencing.Registry HOT 2
- validate fails to identify incorrect uuid strings HOT 3
- 'Tuple' arrays not handled correctly HOT 3
- validate() throwing exception for a valid schema HOT 1
- Draft7Validator(TyperError: create.<locals>.Validator.__init__() got an unexpected keyword argument 'registry' HOT 2
- Which is the last version not requiring Rust via its dependencies?
- Migrating From RefResolver, unable to resolve $ref
- Feature request: Add support for a second message attribute on errors which is guaranteed not to include the failing instance HOT 5
- Python NaN validates against all numeric limits, and shouldn't HOT 2
- validating nan in an enum is no longer supported HOT 1
- Need a custom ref resolver
- `"format":"date-time"` not working HOT 6
- The latest version is slower than 3.2.0 validator HOT 5
- Validation error messages changed after upgrading jsonschema version from 3.2.0 to 4.21.1 HOT 5
- multipleOf fails to validate that 4.02 is a multiple of 0.01 due to floating point math HOT 1
- Unexpected KeyError while running test suite inside GitLab Worker HOT 3
- Enhancing the multipleOf Validator for Improved Decimal Handling in jsonschema HOT 1
- @FormatChecker.checks decorator not a classmethod HOT 1
- RefResolver deprecation docs are confusing and do not explain how to replace a very simple usage (a RefResolver which just specifies a base_uri) HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from jsonschema.