PKG-INFO 22 KB

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