|
3 | 3 | import re |
4 | 4 | from typing import Any, Iterator, List, Union, get_args, get_origin |
5 | 5 |
|
| 6 | +from jsonschema.protocols import Validator as JsonschemaValidator |
| 7 | +from jsonschema.validators import validator_for |
6 | 8 | from pydantic.json_schema import GenerateJsonSchema, JsonSchemaMode, JsonSchemaValue |
7 | 9 | from pydantic_core import CoreSchema, core_schema |
8 | 10 |
|
@@ -136,3 +138,41 @@ def sanitize_value(value: str, field: str = "non-extension", sub: str = "-") -> |
136 | 138 | if field != "extension": |
137 | 139 | value = value.replace(".", sub) |
138 | 140 | return value |
| 141 | + |
| 142 | + |
| 143 | +def jsonschema_validator( |
| 144 | + schema: dict[str, Any], |
| 145 | + *, |
| 146 | + check_format: bool, |
| 147 | + default_cls: type[JsonschemaValidator] | None = None, |
| 148 | +) -> JsonschemaValidator: |
| 149 | + """ |
| 150 | + Create a JSON schema validator appropriate for validating instances against a given |
| 151 | + schema |
| 152 | +
|
| 153 | + :param schema: The JSON schema to validate against |
| 154 | + :param check_format: Indicates whether to check the format against format |
| 155 | + specifications in the schema |
| 156 | + :param default_cls: The default JSON schema validator class to use to create the |
| 157 | + validator should the appropriate validator class cannot be determined based on |
| 158 | + the schema (by assessing the `$schema` property). If `None`, the class |
| 159 | + representing the latest JSON schema draft supported by the `jsonschema` package. |
| 160 | + :return: The JSON schema validator |
| 161 | + :raises jsonschema.exceptions.SchemaError: If the JSON schema is invalid |
| 162 | + """ |
| 163 | + # Retrieve appropriate validator class for validating the given schema |
| 164 | + validator_cls = ( |
| 165 | + validator_for(schema, default_cls) |
| 166 | + if default_cls is not None |
| 167 | + else validator_for(schema) |
| 168 | + ) |
| 169 | + |
| 170 | + # Ensure the schema is valid |
| 171 | + validator_cls.check_schema(schema) |
| 172 | + |
| 173 | + if check_format: |
| 174 | + # Return a validator with format checking enabled |
| 175 | + return validator_cls(schema, format_checker=validator_cls.FORMAT_CHECKER) |
| 176 | + |
| 177 | + # Return a validator with format checking disabled |
| 178 | + return validator_cls(schema) |
0 commit comments