validators.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. """
  2. Creation and extension of validators, with implementations for existing drafts.
  3. """
  4. from __future__ import division
  5. from warnings import warn
  6. import contextlib
  7. import json
  8. import numbers
  9. from six import add_metaclass
  10. from jsonschema import (
  11. _legacy_validators,
  12. _types,
  13. _utils,
  14. _validators,
  15. exceptions,
  16. )
  17. from jsonschema.compat import (
  18. Sequence,
  19. int_types,
  20. iteritems,
  21. lru_cache,
  22. str_types,
  23. unquote,
  24. urldefrag,
  25. urljoin,
  26. urlopen,
  27. urlsplit,
  28. )
  29. # Sigh. https://gitlab.com/pycqa/flake8/issues/280
  30. # https://github.com/pyga/ebb-lint/issues/7
  31. # Imported for backwards compatibility.
  32. from jsonschema.exceptions import ErrorTree
  33. ErrorTree
  34. class _DontDoThat(Exception):
  35. """
  36. Raised when a Validators with non-default type checker is misused.
  37. Asking one for DEFAULT_TYPES doesn't make sense, since type checkers
  38. exist for the unrepresentable cases where DEFAULT_TYPES can't
  39. represent the type relationship.
  40. """
  41. def __str__(self):
  42. return "DEFAULT_TYPES cannot be used on Validators using TypeCheckers"
  43. validators = {}
  44. meta_schemas = _utils.URIDict()
  45. def _generate_legacy_type_checks(types=()):
  46. """
  47. Generate newer-style type checks out of JSON-type-name-to-type mappings.
  48. Arguments:
  49. types (dict):
  50. A mapping of type names to their Python types
  51. Returns:
  52. A dictionary of definitions to pass to `TypeChecker`
  53. """
  54. types = dict(types)
  55. def gen_type_check(pytypes):
  56. pytypes = _utils.flatten(pytypes)
  57. def type_check(checker, instance):
  58. if isinstance(instance, bool):
  59. if bool not in pytypes:
  60. return False
  61. return isinstance(instance, pytypes)
  62. return type_check
  63. definitions = {}
  64. for typename, pytypes in iteritems(types):
  65. definitions[typename] = gen_type_check(pytypes)
  66. return definitions
  67. _DEPRECATED_DEFAULT_TYPES = {
  68. u"array": list,
  69. u"boolean": bool,
  70. u"integer": int_types,
  71. u"null": type(None),
  72. u"number": numbers.Number,
  73. u"object": dict,
  74. u"string": str_types,
  75. }
  76. _TYPE_CHECKER_FOR_DEPRECATED_DEFAULT_TYPES = _types.TypeChecker(
  77. type_checkers=_generate_legacy_type_checks(_DEPRECATED_DEFAULT_TYPES),
  78. )
  79. def validates(version):
  80. """
  81. Register the decorated validator for a ``version`` of the specification.
  82. Registered validators and their meta schemas will be considered when
  83. parsing ``$schema`` properties' URIs.
  84. Arguments:
  85. version (str):
  86. An identifier to use as the version's name
  87. Returns:
  88. collections.Callable:
  89. a class decorator to decorate the validator with the version
  90. """
  91. def _validates(cls):
  92. validators[version] = cls
  93. meta_schema_id = cls.ID_OF(cls.META_SCHEMA)
  94. if meta_schema_id:
  95. meta_schemas[meta_schema_id] = cls
  96. return cls
  97. return _validates
  98. def _DEFAULT_TYPES(self):
  99. if self._CREATED_WITH_DEFAULT_TYPES is None:
  100. raise _DontDoThat()
  101. warn(
  102. (
  103. "The DEFAULT_TYPES attribute is deprecated. "
  104. "See the type checker attached to this validator instead."
  105. ),
  106. DeprecationWarning,
  107. stacklevel=2,
  108. )
  109. return self._DEFAULT_TYPES
  110. class _DefaultTypesDeprecatingMetaClass(type):
  111. DEFAULT_TYPES = property(_DEFAULT_TYPES)
  112. def _id_of(schema):
  113. if schema is True or schema is False:
  114. return u""
  115. return schema.get(u"$id", u"")
  116. def create(
  117. meta_schema,
  118. validators=(),
  119. version=None,
  120. default_types=None,
  121. type_checker=None,
  122. id_of=_id_of,
  123. ):
  124. """
  125. Create a new validator class.
  126. Arguments:
  127. meta_schema (collections.Mapping):
  128. the meta schema for the new validator class
  129. validators (collections.Mapping):
  130. a mapping from names to callables, where each callable will
  131. validate the schema property with the given name.
  132. Each callable should take 4 arguments:
  133. 1. a validator instance,
  134. 2. the value of the property being validated within the
  135. instance
  136. 3. the instance
  137. 4. the schema
  138. version (str):
  139. an identifier for the version that this validator class will
  140. validate. If provided, the returned validator class will
  141. have its ``__name__`` set to include the version, and also
  142. will have `jsonschema.validators.validates` automatically
  143. called for the given version.
  144. type_checker (jsonschema.TypeChecker):
  145. a type checker, used when applying the :validator:`type` validator.
  146. If unprovided, a `jsonschema.TypeChecker` will be created
  147. with a set of default types typical of JSON Schema drafts.
  148. default_types (collections.Mapping):
  149. .. deprecated:: 3.0.0
  150. Please use the type_checker argument instead.
  151. If set, it provides mappings of JSON types to Python types
  152. that will be converted to functions and redefined in this
  153. object's `jsonschema.TypeChecker`.
  154. id_of (collections.Callable):
  155. A function that given a schema, returns its ID.
  156. Returns:
  157. a new `jsonschema.IValidator` class
  158. """
  159. if default_types is not None:
  160. if type_checker is not None:
  161. raise TypeError(
  162. "Do not specify default_types when providing a type checker.",
  163. )
  164. _created_with_default_types = True
  165. warn(
  166. (
  167. "The default_types argument is deprecated. "
  168. "Use the type_checker argument instead."
  169. ),
  170. DeprecationWarning,
  171. stacklevel=2,
  172. )
  173. type_checker = _types.TypeChecker(
  174. type_checkers=_generate_legacy_type_checks(default_types),
  175. )
  176. else:
  177. default_types = _DEPRECATED_DEFAULT_TYPES
  178. if type_checker is None:
  179. _created_with_default_types = False
  180. type_checker = _TYPE_CHECKER_FOR_DEPRECATED_DEFAULT_TYPES
  181. elif type_checker is _TYPE_CHECKER_FOR_DEPRECATED_DEFAULT_TYPES:
  182. _created_with_default_types = False
  183. else:
  184. _created_with_default_types = None
  185. @add_metaclass(_DefaultTypesDeprecatingMetaClass)
  186. class Validator(object):
  187. VALIDATORS = dict(validators)
  188. META_SCHEMA = dict(meta_schema)
  189. TYPE_CHECKER = type_checker
  190. ID_OF = staticmethod(id_of)
  191. DEFAULT_TYPES = property(_DEFAULT_TYPES)
  192. _DEFAULT_TYPES = dict(default_types)
  193. _CREATED_WITH_DEFAULT_TYPES = _created_with_default_types
  194. def __init__(
  195. self,
  196. schema,
  197. types=(),
  198. resolver=None,
  199. format_checker=None,
  200. ):
  201. if types:
  202. warn(
  203. (
  204. "The types argument is deprecated. Provide "
  205. "a type_checker to jsonschema.validators.extend "
  206. "instead."
  207. ),
  208. DeprecationWarning,
  209. stacklevel=2,
  210. )
  211. self.TYPE_CHECKER = self.TYPE_CHECKER.redefine_many(
  212. _generate_legacy_type_checks(types),
  213. )
  214. if resolver is None:
  215. resolver = RefResolver.from_schema(schema, id_of=id_of)
  216. self.resolver = resolver
  217. self.format_checker = format_checker
  218. self.schema = schema
  219. @classmethod
  220. def check_schema(cls, schema):
  221. for error in cls(cls.META_SCHEMA).iter_errors(schema):
  222. raise exceptions.SchemaError.create_from(error)
  223. def iter_errors(self, instance, _schema=None):
  224. if _schema is None:
  225. _schema = self.schema
  226. if _schema is True:
  227. return
  228. elif _schema is False:
  229. yield exceptions.ValidationError(
  230. "False schema does not allow %r" % (instance,),
  231. validator=None,
  232. validator_value=None,
  233. instance=instance,
  234. schema=_schema,
  235. )
  236. return
  237. scope = id_of(_schema)
  238. if scope:
  239. self.resolver.push_scope(scope)
  240. try:
  241. ref = _schema.get(u"$ref")
  242. if ref is not None:
  243. validators = [(u"$ref", ref)]
  244. else:
  245. validators = iteritems(_schema)
  246. for k, v in validators:
  247. validator = self.VALIDATORS.get(k)
  248. if validator is None:
  249. continue
  250. errors = validator(self, v, instance, _schema) or ()
  251. for error in errors:
  252. # set details if not already set by the called fn
  253. error._set(
  254. validator=k,
  255. validator_value=v,
  256. instance=instance,
  257. schema=_schema,
  258. )
  259. if k != u"$ref":
  260. error.schema_path.appendleft(k)
  261. yield error
  262. finally:
  263. if scope:
  264. self.resolver.pop_scope()
  265. def descend(self, instance, schema, path=None, schema_path=None):
  266. for error in self.iter_errors(instance, schema):
  267. if path is not None:
  268. error.path.appendleft(path)
  269. if schema_path is not None:
  270. error.schema_path.appendleft(schema_path)
  271. yield error
  272. def validate(self, *args, **kwargs):
  273. for error in self.iter_errors(*args, **kwargs):
  274. raise error
  275. def is_type(self, instance, type):
  276. try:
  277. return self.TYPE_CHECKER.is_type(instance, type)
  278. except exceptions.UndefinedTypeCheck:
  279. raise exceptions.UnknownType(type, instance, self.schema)
  280. def is_valid(self, instance, _schema=None):
  281. error = next(self.iter_errors(instance, _schema), None)
  282. return error is None
  283. if version is not None:
  284. Validator = validates(version)(Validator)
  285. Validator.__name__ = version.title().replace(" ", "") + "Validator"
  286. return Validator
  287. def extend(validator, validators=(), version=None, type_checker=None):
  288. """
  289. Create a new validator class by extending an existing one.
  290. Arguments:
  291. validator (jsonschema.IValidator):
  292. an existing validator class
  293. validators (collections.Mapping):
  294. a mapping of new validator callables to extend with, whose
  295. structure is as in `create`.
  296. .. note::
  297. Any validator callables with the same name as an
  298. existing one will (silently) replace the old validator
  299. callable entirely, effectively overriding any validation
  300. done in the "parent" validator class.
  301. If you wish to instead extend the behavior of a parent's
  302. validator callable, delegate and call it directly in
  303. the new validator function by retrieving it using
  304. ``OldValidator.VALIDATORS["validator_name"]``.
  305. version (str):
  306. a version for the new validator class
  307. type_checker (jsonschema.TypeChecker):
  308. a type checker, used when applying the :validator:`type` validator.
  309. If unprovided, the type checker of the extended
  310. `jsonschema.IValidator` will be carried along.`
  311. Returns:
  312. a new `jsonschema.IValidator` class extending the one provided
  313. .. note:: Meta Schemas
  314. The new validator class will have its parent's meta schema.
  315. If you wish to change or extend the meta schema in the new
  316. validator class, modify ``META_SCHEMA`` directly on the returned
  317. class. Note that no implicit copying is done, so a copy should
  318. likely be made before modifying it, in order to not affect the
  319. old validator.
  320. """
  321. all_validators = dict(validator.VALIDATORS)
  322. all_validators.update(validators)
  323. if type_checker is None:
  324. type_checker = validator.TYPE_CHECKER
  325. elif validator._CREATED_WITH_DEFAULT_TYPES:
  326. raise TypeError(
  327. "Cannot extend a validator created with default_types "
  328. "with a type_checker. Update the validator to use a "
  329. "type_checker when created."
  330. )
  331. return create(
  332. meta_schema=validator.META_SCHEMA,
  333. validators=all_validators,
  334. version=version,
  335. type_checker=type_checker,
  336. id_of=validator.ID_OF,
  337. )
  338. Draft3Validator = create(
  339. meta_schema=_utils.load_schema("draft3"),
  340. validators={
  341. u"$ref": _validators.ref,
  342. u"additionalItems": _validators.additionalItems,
  343. u"additionalProperties": _validators.additionalProperties,
  344. u"dependencies": _legacy_validators.dependencies_draft3,
  345. u"disallow": _legacy_validators.disallow_draft3,
  346. u"divisibleBy": _validators.multipleOf,
  347. u"enum": _validators.enum,
  348. u"extends": _legacy_validators.extends_draft3,
  349. u"format": _validators.format,
  350. u"items": _legacy_validators.items_draft3_draft4,
  351. u"maxItems": _validators.maxItems,
  352. u"maxLength": _validators.maxLength,
  353. u"maximum": _legacy_validators.maximum_draft3_draft4,
  354. u"minItems": _validators.minItems,
  355. u"minLength": _validators.minLength,
  356. u"minimum": _legacy_validators.minimum_draft3_draft4,
  357. u"pattern": _validators.pattern,
  358. u"patternProperties": _validators.patternProperties,
  359. u"properties": _legacy_validators.properties_draft3,
  360. u"type": _legacy_validators.type_draft3,
  361. u"uniqueItems": _validators.uniqueItems,
  362. },
  363. type_checker=_types.draft3_type_checker,
  364. version="draft3",
  365. id_of=lambda schema: schema.get(u"id", ""),
  366. )
  367. Draft4Validator = create(
  368. meta_schema=_utils.load_schema("draft4"),
  369. validators={
  370. u"$ref": _validators.ref,
  371. u"additionalItems": _validators.additionalItems,
  372. u"additionalProperties": _validators.additionalProperties,
  373. u"allOf": _validators.allOf,
  374. u"anyOf": _validators.anyOf,
  375. u"dependencies": _validators.dependencies,
  376. u"enum": _validators.enum,
  377. u"format": _validators.format,
  378. u"items": _legacy_validators.items_draft3_draft4,
  379. u"maxItems": _validators.maxItems,
  380. u"maxLength": _validators.maxLength,
  381. u"maxProperties": _validators.maxProperties,
  382. u"maximum": _legacy_validators.maximum_draft3_draft4,
  383. u"minItems": _validators.minItems,
  384. u"minLength": _validators.minLength,
  385. u"minProperties": _validators.minProperties,
  386. u"minimum": _legacy_validators.minimum_draft3_draft4,
  387. u"multipleOf": _validators.multipleOf,
  388. u"not": _validators.not_,
  389. u"oneOf": _validators.oneOf,
  390. u"pattern": _validators.pattern,
  391. u"patternProperties": _validators.patternProperties,
  392. u"properties": _validators.properties,
  393. u"required": _validators.required,
  394. u"type": _validators.type,
  395. u"uniqueItems": _validators.uniqueItems,
  396. },
  397. type_checker=_types.draft4_type_checker,
  398. version="draft4",
  399. id_of=lambda schema: schema.get(u"id", ""),
  400. )
  401. Draft6Validator = create(
  402. meta_schema=_utils.load_schema("draft6"),
  403. validators={
  404. u"$ref": _validators.ref,
  405. u"additionalItems": _validators.additionalItems,
  406. u"additionalProperties": _validators.additionalProperties,
  407. u"allOf": _validators.allOf,
  408. u"anyOf": _validators.anyOf,
  409. u"const": _validators.const,
  410. u"contains": _validators.contains,
  411. u"dependencies": _validators.dependencies,
  412. u"enum": _validators.enum,
  413. u"exclusiveMaximum": _validators.exclusiveMaximum,
  414. u"exclusiveMinimum": _validators.exclusiveMinimum,
  415. u"format": _validators.format,
  416. u"items": _validators.items,
  417. u"maxItems": _validators.maxItems,
  418. u"maxLength": _validators.maxLength,
  419. u"maxProperties": _validators.maxProperties,
  420. u"maximum": _validators.maximum,
  421. u"minItems": _validators.minItems,
  422. u"minLength": _validators.minLength,
  423. u"minProperties": _validators.minProperties,
  424. u"minimum": _validators.minimum,
  425. u"multipleOf": _validators.multipleOf,
  426. u"not": _validators.not_,
  427. u"oneOf": _validators.oneOf,
  428. u"pattern": _validators.pattern,
  429. u"patternProperties": _validators.patternProperties,
  430. u"properties": _validators.properties,
  431. u"propertyNames": _validators.propertyNames,
  432. u"required": _validators.required,
  433. u"type": _validators.type,
  434. u"uniqueItems": _validators.uniqueItems,
  435. },
  436. type_checker=_types.draft6_type_checker,
  437. version="draft6",
  438. )
  439. Draft7Validator = create(
  440. meta_schema=_utils.load_schema("draft7"),
  441. validators={
  442. u"$ref": _validators.ref,
  443. u"additionalItems": _validators.additionalItems,
  444. u"additionalProperties": _validators.additionalProperties,
  445. u"allOf": _validators.allOf,
  446. u"anyOf": _validators.anyOf,
  447. u"const": _validators.const,
  448. u"contains": _validators.contains,
  449. u"dependencies": _validators.dependencies,
  450. u"enum": _validators.enum,
  451. u"exclusiveMaximum": _validators.exclusiveMaximum,
  452. u"exclusiveMinimum": _validators.exclusiveMinimum,
  453. u"format": _validators.format,
  454. u"if": _validators.if_,
  455. u"items": _validators.items,
  456. u"maxItems": _validators.maxItems,
  457. u"maxLength": _validators.maxLength,
  458. u"maxProperties": _validators.maxProperties,
  459. u"maximum": _validators.maximum,
  460. u"minItems": _validators.minItems,
  461. u"minLength": _validators.minLength,
  462. u"minProperties": _validators.minProperties,
  463. u"minimum": _validators.minimum,
  464. u"multipleOf": _validators.multipleOf,
  465. u"oneOf": _validators.oneOf,
  466. u"not": _validators.not_,
  467. u"pattern": _validators.pattern,
  468. u"patternProperties": _validators.patternProperties,
  469. u"properties": _validators.properties,
  470. u"propertyNames": _validators.propertyNames,
  471. u"required": _validators.required,
  472. u"type": _validators.type,
  473. u"uniqueItems": _validators.uniqueItems,
  474. },
  475. type_checker=_types.draft7_type_checker,
  476. version="draft7",
  477. )
  478. _LATEST_VERSION = Draft7Validator
  479. class RefResolver(object):
  480. """
  481. Resolve JSON References.
  482. Arguments:
  483. base_uri (str):
  484. The URI of the referring document
  485. referrer:
  486. The actual referring document
  487. store (dict):
  488. A mapping from URIs to documents to cache
  489. cache_remote (bool):
  490. Whether remote refs should be cached after first resolution
  491. handlers (dict):
  492. A mapping from URI schemes to functions that should be used
  493. to retrieve them
  494. urljoin_cache (:func:`functools.lru_cache`):
  495. A cache that will be used for caching the results of joining
  496. the resolution scope to subscopes.
  497. remote_cache (:func:`functools.lru_cache`):
  498. A cache that will be used for caching the results of
  499. resolved remote URLs.
  500. Attributes:
  501. cache_remote (bool):
  502. Whether remote refs should be cached after first resolution
  503. """
  504. def __init__(
  505. self,
  506. base_uri,
  507. referrer,
  508. store=(),
  509. cache_remote=True,
  510. handlers=(),
  511. urljoin_cache=None,
  512. remote_cache=None,
  513. ):
  514. if urljoin_cache is None:
  515. urljoin_cache = lru_cache(1024)(urljoin)
  516. if remote_cache is None:
  517. remote_cache = lru_cache(1024)(self.resolve_from_url)
  518. self.referrer = referrer
  519. self.cache_remote = cache_remote
  520. self.handlers = dict(handlers)
  521. self._scopes_stack = [base_uri]
  522. self.store = _utils.URIDict(
  523. (id, validator.META_SCHEMA)
  524. for id, validator in iteritems(meta_schemas)
  525. )
  526. self.store.update(store)
  527. self.store[base_uri] = referrer
  528. self._urljoin_cache = urljoin_cache
  529. self._remote_cache = remote_cache
  530. @classmethod
  531. def from_schema(cls, schema, id_of=_id_of, *args, **kwargs):
  532. """
  533. Construct a resolver from a JSON schema object.
  534. Arguments:
  535. schema:
  536. the referring schema
  537. Returns:
  538. `RefResolver`
  539. """
  540. return cls(base_uri=id_of(schema), referrer=schema, *args, **kwargs)
  541. def push_scope(self, scope):
  542. """
  543. Enter a given sub-scope.
  544. Treats further dereferences as being performed underneath the
  545. given scope.
  546. """
  547. self._scopes_stack.append(
  548. self._urljoin_cache(self.resolution_scope, scope),
  549. )
  550. def pop_scope(self):
  551. """
  552. Exit the most recent entered scope.
  553. Treats further dereferences as being performed underneath the
  554. original scope.
  555. Don't call this method more times than `push_scope` has been
  556. called.
  557. """
  558. try:
  559. self._scopes_stack.pop()
  560. except IndexError:
  561. raise exceptions.RefResolutionError(
  562. "Failed to pop the scope from an empty stack. "
  563. "`pop_scope()` should only be called once for every "
  564. "`push_scope()`"
  565. )
  566. @property
  567. def resolution_scope(self):
  568. """
  569. Retrieve the current resolution scope.
  570. """
  571. return self._scopes_stack[-1]
  572. @property
  573. def base_uri(self):
  574. """
  575. Retrieve the current base URI, not including any fragment.
  576. """
  577. uri, _ = urldefrag(self.resolution_scope)
  578. return uri
  579. @contextlib.contextmanager
  580. def in_scope(self, scope):
  581. """
  582. Temporarily enter the given scope for the duration of the context.
  583. """
  584. self.push_scope(scope)
  585. try:
  586. yield
  587. finally:
  588. self.pop_scope()
  589. @contextlib.contextmanager
  590. def resolving(self, ref):
  591. """
  592. Resolve the given ``ref`` and enter its resolution scope.
  593. Exits the scope on exit of this context manager.
  594. Arguments:
  595. ref (str):
  596. The reference to resolve
  597. """
  598. url, resolved = self.resolve(ref)
  599. self.push_scope(url)
  600. try:
  601. yield resolved
  602. finally:
  603. self.pop_scope()
  604. def resolve(self, ref):
  605. """
  606. Resolve the given reference.
  607. """
  608. url = self._urljoin_cache(self.resolution_scope, ref)
  609. return url, self._remote_cache(url)
  610. def resolve_from_url(self, url):
  611. """
  612. Resolve the given remote URL.
  613. """
  614. url, fragment = urldefrag(url)
  615. try:
  616. document = self.store[url]
  617. except KeyError:
  618. try:
  619. document = self.resolve_remote(url)
  620. except Exception as exc:
  621. raise exceptions.RefResolutionError(exc)
  622. return self.resolve_fragment(document, fragment)
  623. def resolve_fragment(self, document, fragment):
  624. """
  625. Resolve a ``fragment`` within the referenced ``document``.
  626. Arguments:
  627. document:
  628. The referent document
  629. fragment (str):
  630. a URI fragment to resolve within it
  631. """
  632. fragment = fragment.lstrip(u"/")
  633. parts = unquote(fragment).split(u"/") if fragment else []
  634. for part in parts:
  635. part = part.replace(u"~1", u"/").replace(u"~0", u"~")
  636. if isinstance(document, Sequence):
  637. # Array indexes should be turned into integers
  638. try:
  639. part = int(part)
  640. except ValueError:
  641. pass
  642. try:
  643. document = document[part]
  644. except (TypeError, LookupError):
  645. raise exceptions.RefResolutionError(
  646. "Unresolvable JSON pointer: %r" % fragment
  647. )
  648. return document
  649. def resolve_remote(self, uri):
  650. """
  651. Resolve a remote ``uri``.
  652. If called directly, does not check the store first, but after
  653. retrieving the document at the specified URI it will be saved in
  654. the store if :attr:`cache_remote` is True.
  655. .. note::
  656. If the requests_ library is present, ``jsonschema`` will use it to
  657. request the remote ``uri``, so that the correct encoding is
  658. detected and used.
  659. If it isn't, or if the scheme of the ``uri`` is not ``http`` or
  660. ``https``, UTF-8 is assumed.
  661. Arguments:
  662. uri (str):
  663. The URI to resolve
  664. Returns:
  665. The retrieved document
  666. .. _requests: https://pypi.org/project/requests/
  667. """
  668. try:
  669. import requests
  670. except ImportError:
  671. requests = None
  672. scheme = urlsplit(uri).scheme
  673. if scheme in self.handlers:
  674. result = self.handlers[scheme](uri)
  675. elif scheme in [u"http", u"https"] and requests:
  676. # Requests has support for detecting the correct encoding of
  677. # json over http
  678. result = requests.get(uri).json()
  679. else:
  680. # Otherwise, pass off to urllib and assume utf-8
  681. with urlopen(uri) as url:
  682. result = json.loads(url.read().decode("utf-8"))
  683. if self.cache_remote:
  684. self.store[uri] = result
  685. return result
  686. def validate(instance, schema, cls=None, *args, **kwargs):
  687. """
  688. Validate an instance under the given schema.
  689. >>> validate([2, 3, 4], {"maxItems": 2})
  690. Traceback (most recent call last):
  691. ...
  692. ValidationError: [2, 3, 4] is too long
  693. :func:`validate` will first verify that the provided schema is
  694. itself valid, since not doing so can lead to less obvious error
  695. messages and fail in less obvious or consistent ways.
  696. If you know you have a valid schema already, especially if you
  697. intend to validate multiple instances with the same schema, you
  698. likely would prefer using the `IValidator.validate` method directly
  699. on a specific validator (e.g. ``Draft7Validator.validate``).
  700. Arguments:
  701. instance:
  702. The instance to validate
  703. schema:
  704. The schema to validate with
  705. cls (IValidator):
  706. The class that will be used to validate the instance.
  707. If the ``cls`` argument is not provided, two things will happen
  708. in accordance with the specification. First, if the schema has a
  709. :validator:`$schema` property containing a known meta-schema [#]_
  710. then the proper validator will be used. The specification recommends
  711. that all schemas contain :validator:`$schema` properties for this
  712. reason. If no :validator:`$schema` property is found, the default
  713. validator class is the latest released draft.
  714. Any other provided positional and keyword arguments will be passed
  715. on when instantiating the ``cls``.
  716. Raises:
  717. `jsonschema.exceptions.ValidationError` if the instance
  718. is invalid
  719. `jsonschema.exceptions.SchemaError` if the schema itself
  720. is invalid
  721. .. rubric:: Footnotes
  722. .. [#] known by a validator registered with
  723. `jsonschema.validators.validates`
  724. """
  725. if cls is None:
  726. cls = validator_for(schema)
  727. cls.check_schema(schema)
  728. validator = cls(schema, *args, **kwargs)
  729. error = exceptions.best_match(validator.iter_errors(instance))
  730. if error is not None:
  731. raise error
  732. def validator_for(schema, default=_LATEST_VERSION):
  733. """
  734. Retrieve the validator class appropriate for validating the given schema.
  735. Uses the :validator:`$schema` property that should be present in the
  736. given schema to look up the appropriate validator class.
  737. Arguments:
  738. schema (collections.Mapping or bool):
  739. the schema to look at
  740. default:
  741. the default to return if the appropriate validator class
  742. cannot be determined.
  743. If unprovided, the default is to return the latest supported
  744. draft.
  745. """
  746. if schema is True or schema is False or u"$schema" not in schema:
  747. return default
  748. if schema[u"$schema"] not in meta_schemas:
  749. warn(
  750. (
  751. "The metaschema specified by $schema was not found. "
  752. "Using the latest draft to validate, but this will raise "
  753. "an error in the future."
  754. ),
  755. DeprecationWarning,
  756. stacklevel=2,
  757. )
  758. return meta_schemas.get(schema[u"$schema"], _LATEST_VERSION)