METADATA 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. Metadata-Version: 2.0
  2. Name: voluptuous
  3. Version: 0.10.5
  4. Summary: # Voluptuous is a Python data validation library
  5. Home-page: https://github.com/alecthomas/voluptuous
  6. Author: Alec Thomas
  7. Author-email: alec@swapoff.org
  8. License: BSD
  9. Download-URL: https://pypi.python.org/pypi/voluptuous
  10. Platform: any
  11. Classifier: Development Status :: 5 - Production/Stable
  12. Classifier: Intended Audience :: Developers
  13. Classifier: License :: OSI Approved :: BSD License
  14. Classifier: Operating System :: OS Independent
  15. Classifier: Programming Language :: Python :: 2
  16. Classifier: Programming Language :: Python :: 2.7
  17. Classifier: Programming Language :: Python :: 3
  18. Classifier: Programming Language :: Python :: 3.1
  19. Classifier: Programming Language :: Python :: 3.2
  20. Classifier: Programming Language :: Python :: 3.3
  21. Classifier: Programming Language :: Python :: 3.4
  22. # Voluptuous is a Python data validation library
  23. [![Build Status](https://travis-ci.org/alecthomas/voluptuous.png)](https://travis-ci.org/alecthomas/voluptuous)
  24. [![Coverage Status](https://coveralls.io/repos/github/alecthomas/voluptuous/badge.svg?branch=master)](https://coveralls.io/github/alecthomas/voluptuous?branch=master) [![Gitter chat](https://badges.gitter.im/alecthomas.png)](https://gitter.im/alecthomas/Lobby)
  25. Voluptuous, *despite* the name, is a Python data validation library. It
  26. is primarily intended for validating data coming into Python as JSON,
  27. YAML, etc.
  28. It has three goals:
  29. 1. Simplicity.
  30. 2. Support for complex data structures.
  31. 3. Provide useful error messages.
  32. ## Contact
  33. Voluptuous now has a mailing list! Send a mail to
  34. [<voluptuous@librelist.com>](mailto:voluptuous@librelist.com) to subscribe. Instructions
  35. will follow.
  36. You can also contact me directly via [email](mailto:alec@swapoff.org) or
  37. [Twitter](https://twitter.com/alecthomas).
  38. To file a bug, create a [new issue](https://github.com/alecthomas/voluptuous/issues/new) on GitHub with a short example of how to replicate the issue.
  39. ## Documentation
  40. The documentation is provided [here] (http://alecthomas.github.io/voluptuous/).
  41. ## Changelog
  42. See [CHANGELOG.md](CHANGELOG.md).
  43. ## Show me an example
  44. Twitter's [user search API](https://dev.twitter.com/rest/reference/get/users/search) accepts
  45. query URLs like:
  46. ```
  47. $ curl 'http://api.twitter.com/1.1/users/search.json?q=python&per_page=20&page=1'
  48. ```
  49. To validate this we might use a schema like:
  50. ```pycon
  51. >>> from voluptuous import Schema
  52. >>> schema = Schema({
  53. ... 'q': str,
  54. ... 'per_page': int,
  55. ... 'page': int,
  56. ... })
  57. ```
  58. This schema very succinctly and roughly describes the data required by
  59. the API, and will work fine. But it has a few problems. Firstly, it
  60. doesn't fully express the constraints of the API. According to the API,
  61. `per_page` should be restricted to at most 20, defaulting to 5, for
  62. example. To describe the semantics of the API more accurately, our
  63. schema will need to be more thoroughly defined:
  64. ```pycon
  65. >>> from voluptuous import Required, All, Length, Range
  66. >>> schema = Schema({
  67. ... Required('q'): All(str, Length(min=1)),
  68. ... Required('per_page', default=5): All(int, Range(min=1, max=20)),
  69. ... 'page': All(int, Range(min=0)),
  70. ... })
  71. ```
  72. This schema fully enforces the interface defined in Twitter's
  73. documentation, and goes a little further for completeness.
  74. "q" is required:
  75. ```pycon
  76. >>> from voluptuous import MultipleInvalid, Invalid
  77. >>> try:
  78. ... schema({})
  79. ... raise AssertionError('MultipleInvalid not raised')
  80. ... except MultipleInvalid as e:
  81. ... exc = e
  82. >>> str(exc) == "required key not provided @ data['q']"
  83. True
  84. ```
  85. ...must be a string:
  86. ```pycon
  87. >>> try:
  88. ... schema({'q': 123})
  89. ... raise AssertionError('MultipleInvalid not raised')
  90. ... except MultipleInvalid as e:
  91. ... exc = e
  92. >>> str(exc) == "expected str for dictionary value @ data['q']"
  93. True
  94. ```
  95. ...and must be at least one character in length:
  96. ```pycon
  97. >>> try:
  98. ... schema({'q': ''})
  99. ... raise AssertionError('MultipleInvalid not raised')
  100. ... except MultipleInvalid as e:
  101. ... exc = e
  102. >>> str(exc) == "length of value must be at least 1 for dictionary value @ data['q']"
  103. True
  104. >>> schema({'q': '#topic'}) == {'q': '#topic', 'per_page': 5}
  105. True
  106. ```
  107. "per\_page" is a positive integer no greater than 20:
  108. ```pycon
  109. >>> try:
  110. ... schema({'q': '#topic', 'per_page': 900})
  111. ... raise AssertionError('MultipleInvalid not raised')
  112. ... except MultipleInvalid as e:
  113. ... exc = e
  114. >>> str(exc) == "value must be at most 20 for dictionary value @ data['per_page']"
  115. True
  116. >>> try:
  117. ... schema({'q': '#topic', 'per_page': -10})
  118. ... raise AssertionError('MultipleInvalid not raised')
  119. ... except MultipleInvalid as e:
  120. ... exc = e
  121. >>> str(exc) == "value must be at least 1 for dictionary value @ data['per_page']"
  122. True
  123. ```
  124. "page" is an integer \>= 0:
  125. ```pycon
  126. >>> try:
  127. ... schema({'q': '#topic', 'per_page': 'one'})
  128. ... raise AssertionError('MultipleInvalid not raised')
  129. ... except MultipleInvalid as e:
  130. ... exc = e
  131. >>> str(exc)
  132. "expected int for dictionary value @ data['per_page']"
  133. >>> schema({'q': '#topic', 'page': 1}) == {'q': '#topic', 'page': 1, 'per_page': 5}
  134. True
  135. ```
  136. ## Defining schemas
  137. Schemas are nested data structures consisting of dictionaries, lists,
  138. scalars and *validators*. Each node in the input schema is pattern
  139. matched against corresponding nodes in the input data.
  140. ### Literals
  141. Literals in the schema are matched using normal equality checks:
  142. ```pycon
  143. >>> schema = Schema(1)
  144. >>> schema(1)
  145. 1
  146. >>> schema = Schema('a string')
  147. >>> schema('a string')
  148. 'a string'
  149. ```
  150. ### Types
  151. Types in the schema are matched by checking if the corresponding value
  152. is an instance of the type:
  153. ```pycon
  154. >>> schema = Schema(int)
  155. >>> schema(1)
  156. 1
  157. >>> try:
  158. ... schema('one')
  159. ... raise AssertionError('MultipleInvalid not raised')
  160. ... except MultipleInvalid as e:
  161. ... exc = e
  162. >>> str(exc) == "expected int"
  163. True
  164. ```
  165. ### URL's
  166. URL's in the schema are matched by using `urlparse` library.
  167. ```pycon
  168. >>> from voluptuous import Url
  169. >>> schema = Schema(Url())
  170. >>> schema('http://w3.org')
  171. 'http://w3.org'
  172. >>> try:
  173. ... schema('one')
  174. ... raise AssertionError('MultipleInvalid not raised')
  175. ... except MultipleInvalid as e:
  176. ... exc = e
  177. >>> str(exc) == "expected a URL"
  178. True
  179. ```
  180. ### Lists
  181. Lists in the schema are treated as a set of valid values. Each element
  182. in the schema list is compared to each value in the input data:
  183. ```pycon
  184. >>> schema = Schema([1, 'a', 'string'])
  185. >>> schema([1])
  186. [1]
  187. >>> schema([1, 1, 1])
  188. [1, 1, 1]
  189. >>> schema(['a', 1, 'string', 1, 'string'])
  190. ['a', 1, 'string', 1, 'string']
  191. ```
  192. However, an empty list (`[]`) is treated as is. If you want to specify a list that can
  193. contain anything, specify it as `list`:
  194. ```pycon
  195. >>> schema = Schema([])
  196. >>> try:
  197. ... schema([1])
  198. ... raise AssertionError('MultipleInvalid not raised')
  199. ... except MultipleInvalid as e:
  200. ... exc = e
  201. >>> str(exc) == "not a valid value"
  202. True
  203. >>> schema([])
  204. []
  205. >>> schema = Schema(list)
  206. >>> schema([])
  207. []
  208. >>> schema([1, 2])
  209. [1, 2]
  210. ```
  211. ### Validation functions
  212. Validators are simple callables that raise an `Invalid` exception when
  213. they encounter invalid data. The criteria for determining validity is
  214. entirely up to the implementation; it may check that a value is a valid
  215. username with `pwd.getpwnam()`, it may check that a value is of a
  216. specific type, and so on.
  217. The simplest kind of validator is a Python function that raises
  218. ValueError when its argument is invalid. Conveniently, many builtin
  219. Python functions have this property. Here's an example of a date
  220. validator:
  221. ```pycon
  222. >>> from datetime import datetime
  223. >>> def Date(fmt='%Y-%m-%d'):
  224. ... return lambda v: datetime.strptime(v, fmt)
  225. ```
  226. ```pycon
  227. >>> schema = Schema(Date())
  228. >>> schema('2013-03-03')
  229. datetime.datetime(2013, 3, 3, 0, 0)
  230. >>> try:
  231. ... schema('2013-03')
  232. ... raise AssertionError('MultipleInvalid not raised')
  233. ... except MultipleInvalid as e:
  234. ... exc = e
  235. >>> str(exc) == "not a valid value"
  236. True
  237. ```
  238. In addition to simply determining if a value is valid, validators may
  239. mutate the value into a valid form. An example of this is the
  240. `Coerce(type)` function, which returns a function that coerces its
  241. argument to the given type:
  242. ```python
  243. def Coerce(type, msg=None):
  244. """Coerce a value to a type.
  245. If the type constructor throws a ValueError, the value will be marked as
  246. Invalid.
  247. """
  248. def f(v):
  249. try:
  250. return type(v)
  251. except ValueError:
  252. raise Invalid(msg or ('expected %s' % type.__name__))
  253. return f
  254. ```
  255. This example also shows a common idiom where an optional human-readable
  256. message can be provided. This can vastly improve the usefulness of the
  257. resulting error messages.
  258. ### Dictionaries
  259. Each key-value pair in a schema dictionary is validated against each
  260. key-value pair in the corresponding data dictionary:
  261. ```pycon
  262. >>> schema = Schema({1: 'one', 2: 'two'})
  263. >>> schema({1: 'one'})
  264. {1: 'one'}
  265. ```
  266. #### Extra dictionary keys
  267. By default any additional keys in the data, not in the schema will
  268. trigger exceptions:
  269. ```pycon
  270. >>> schema = Schema({2: 3})
  271. >>> try:
  272. ... schema({1: 2, 2: 3})
  273. ... raise AssertionError('MultipleInvalid not raised')
  274. ... except MultipleInvalid as e:
  275. ... exc = e
  276. >>> str(exc) == "extra keys not allowed @ data[1]"
  277. True
  278. ```
  279. This behaviour can be altered on a per-schema basis. To allow
  280. additional keys use
  281. `Schema(..., extra=ALLOW_EXTRA)`:
  282. ```pycon
  283. >>> from voluptuous import ALLOW_EXTRA
  284. >>> schema = Schema({2: 3}, extra=ALLOW_EXTRA)
  285. >>> schema({1: 2, 2: 3})
  286. {1: 2, 2: 3}
  287. ```
  288. To remove additional keys use
  289. `Schema(..., extra=REMOVE_EXTRA)`:
  290. ```pycon
  291. >>> from voluptuous import REMOVE_EXTRA
  292. >>> schema = Schema({2: 3}, extra=REMOVE_EXTRA)
  293. >>> schema({1: 2, 2: 3})
  294. {2: 3}
  295. ```
  296. It can also be overridden per-dictionary by using the catch-all marker
  297. token `extra` as a key:
  298. ```pycon
  299. >>> from voluptuous import Extra
  300. >>> schema = Schema({1: {Extra: object}})
  301. >>> schema({1: {'foo': 'bar'}})
  302. {1: {'foo': 'bar'}}
  303. ```
  304. However, an empty dict (`{}`) is treated as is. If you want to specify a list that can
  305. contain anything, specify it as `dict`:
  306. ```pycon
  307. >>> schema = Schema({}, extra=ALLOW_EXTRA) # don't do this
  308. >>> try:
  309. ... schema({'extra': 1})
  310. ... raise AssertionError('MultipleInvalid not raised')
  311. ... except MultipleInvalid as e:
  312. ... exc = e
  313. >>> str(exc) == "not a valid value"
  314. True
  315. >>> schema({})
  316. {}
  317. >>> schema = Schema(dict) # do this instead
  318. >>> schema({})
  319. {}
  320. >>> schema({'extra': 1})
  321. {'extra': 1}
  322. ```
  323. #### Required dictionary keys
  324. By default, keys in the schema are not required to be in the data:
  325. ```pycon
  326. >>> schema = Schema({1: 2, 3: 4})
  327. >>> schema({3: 4})
  328. {3: 4}
  329. ```
  330. Similarly to how extra\_ keys work, this behaviour can be overridden
  331. per-schema:
  332. ```pycon
  333. >>> schema = Schema({1: 2, 3: 4}, required=True)
  334. >>> try:
  335. ... schema({3: 4})
  336. ... raise AssertionError('MultipleInvalid not raised')
  337. ... except MultipleInvalid as e:
  338. ... exc = e
  339. >>> str(exc) == "required key not provided @ data[1]"
  340. True
  341. ```
  342. And per-key, with the marker token `Required(key)`:
  343. ```pycon
  344. >>> schema = Schema({Required(1): 2, 3: 4})
  345. >>> try:
  346. ... schema({3: 4})
  347. ... raise AssertionError('MultipleInvalid not raised')
  348. ... except MultipleInvalid as e:
  349. ... exc = e
  350. >>> str(exc) == "required key not provided @ data[1]"
  351. True
  352. >>> schema({1: 2})
  353. {1: 2}
  354. ```
  355. #### Optional dictionary keys
  356. If a schema has `required=True`, keys may be individually marked as
  357. optional using the marker token `Optional(key)`:
  358. ```pycon
  359. >>> from voluptuous import Optional
  360. >>> schema = Schema({1: 2, Optional(3): 4}, required=True)
  361. >>> try:
  362. ... schema({})
  363. ... raise AssertionError('MultipleInvalid not raised')
  364. ... except MultipleInvalid as e:
  365. ... exc = e
  366. >>> str(exc) == "required key not provided @ data[1]"
  367. True
  368. >>> schema({1: 2})
  369. {1: 2}
  370. >>> try:
  371. ... schema({1: 2, 4: 5})
  372. ... raise AssertionError('MultipleInvalid not raised')
  373. ... except MultipleInvalid as e:
  374. ... exc = e
  375. >>> str(exc) == "extra keys not allowed @ data[4]"
  376. True
  377. ```
  378. ```pycon
  379. >>> schema({1: 2, 3: 4})
  380. {1: 2, 3: 4}
  381. ```
  382. ### Recursive schema
  383. There is no syntax to have a recursive schema. The best way to do it is to have a wrapper like this:
  384. ```pycon
  385. >>> from voluptuous import Schema, Any
  386. >>> def s2(v):
  387. ... return s1(v)
  388. ...
  389. >>> s1 = Schema({"key": Any(s2, "value")})
  390. >>> s1({"key": {"key": "value"}})
  391. {'key': {'key': 'value'}}
  392. ```
  393. ### Extending an existing Schema
  394. Often it comes handy to have a base `Schema` that is extended with more
  395. requirements. In that case you can use `Schema.extend` to create a new
  396. `Schema`:
  397. ```pycon
  398. >>> from voluptuous import Schema
  399. >>> person = Schema({'name': str})
  400. >>> person_with_age = person.extend({'age': int})
  401. >>> sorted(list(person_with_age.schema.keys()))
  402. ['age', 'name']
  403. ```
  404. The original `Schema` remains unchanged.
  405. ### Objects
  406. Each key-value pair in a schema dictionary is validated against each
  407. attribute-value pair in the corresponding object:
  408. ```pycon
  409. >>> from voluptuous import Object
  410. >>> class Structure(object):
  411. ... def __init__(self, q=None):
  412. ... self.q = q
  413. ... def __repr__(self):
  414. ... return '<Structure(q={0.q!r})>'.format(self)
  415. ...
  416. >>> schema = Schema(Object({'q': 'one'}, cls=Structure))
  417. >>> schema(Structure(q='one'))
  418. <Structure(q='one')>
  419. ```
  420. ### Allow None values
  421. To allow value to be None as well, use Any:
  422. ```pycon
  423. >>> from voluptuous import Any
  424. >>> schema = Schema(Any(None, int))
  425. >>> schema(None)
  426. >>> schema(5)
  427. 5
  428. ```
  429. ## Error reporting
  430. Validators must throw an `Invalid` exception if invalid data is passed
  431. to them. All other exceptions are treated as errors in the validator and
  432. will not be caught.
  433. Each `Invalid` exception has an associated `path` attribute representing
  434. the path in the data structure to our currently validating value, as well
  435. as an `error_message` attribute that contains the message of the original
  436. exception. This is especially useful when you want to catch `Invalid`
  437. exceptions and give some feedback to the user, for instance in the context of
  438. an HTTP API.
  439. ```pycon
  440. >>> def validate_email(email):
  441. ... """Validate email."""
  442. ... if not "@" in email:
  443. ... raise Invalid("This email is invalid.")
  444. ... return email
  445. >>> schema = Schema({"email": validate_email})
  446. >>> exc = None
  447. >>> try:
  448. ... schema({"email": "whatever"})
  449. ... except MultipleInvalid as e:
  450. ... exc = e
  451. >>> str(exc)
  452. "This email is invalid. for dictionary value @ data['email']"
  453. >>> exc.path
  454. ['email']
  455. >>> exc.msg
  456. 'This email is invalid.'
  457. >>> exc.error_message
  458. 'This email is invalid.'
  459. ```
  460. The `path` attribute is used during error reporting, but also during matching
  461. to determine whether an error should be reported to the user or if the next
  462. match should be attempted. This is determined by comparing the depth of the
  463. path where the check is, to the depth of the path where the error occurred. If
  464. the error is more than one level deeper, it is reported.
  465. The upshot of this is that *matching is depth-first and fail-fast*.
  466. To illustrate this, here is an example schema:
  467. ```pycon
  468. >>> schema = Schema([[2, 3], 6])
  469. ```
  470. Each value in the top-level list is matched depth-first in-order. Given
  471. input data of `[[6]]`, the inner list will match the first element of
  472. the schema, but the literal `6` will not match any of the elements of
  473. that list. This error will be reported back to the user immediately. No
  474. backtracking is attempted:
  475. ```pycon
  476. >>> try:
  477. ... schema([[6]])
  478. ... raise AssertionError('MultipleInvalid not raised')
  479. ... except MultipleInvalid as e:
  480. ... exc = e
  481. >>> str(exc) == "not a valid value @ data[0][0]"
  482. True
  483. ```
  484. If we pass the data `[6]`, the `6` is not a list type and so will not
  485. recurse into the first element of the schema. Matching will continue on
  486. to the second element in the schema, and succeed:
  487. ```pycon
  488. >>> schema([6])
  489. [6]
  490. ```
  491. ## Running tests.
  492. Voluptuous is using nosetests:
  493. $ nosetests
  494. ## Why use Voluptuous over another validation library?
  495. **Validators are simple callables**
  496. : No need to subclass anything, just use a function.
  497. **Errors are simple exceptions.**
  498. : A validator can just `raise Invalid(msg)` and expect the user to get
  499. useful messages.
  500. **Schemas are basic Python data structures.**
  501. : Should your data be a dictionary of integer keys to strings?
  502. `{int: str}` does what you expect. List of integers, floats or
  503. strings? `[int, float, str]`.
  504. **Designed from the ground up for validating more than just forms.**
  505. : Nested data structures are treated in the same way as any other
  506. type. Need a list of dictionaries? `[{}]`
  507. **Consistency.**
  508. : Types in the schema are checked as types. Values are compared as
  509. values. Callables are called to validate. Simple.
  510. ## Other libraries and inspirations
  511. Voluptuous is heavily inspired by
  512. [Validino](http://code.google.com/p/validino/), and to a lesser extent,
  513. [jsonvalidator](http://code.google.com/p/jsonvalidator/) and
  514. [json\_schema](http://blog.sendapatch.se/category/json_schema.html).
  515. I greatly prefer the light-weight style promoted by these libraries to
  516. the complexity of libraries like FormEncode.