METADATA 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. Metadata-Version: 2.1
  2. Name: wadllib
  3. Version: 1.3.6
  4. Summary: Navigate HTTP resources using WADL files as guides.
  5. Home-page: https://launchpad.net/wadllib
  6. Maintainer: LAZR Developers
  7. Maintainer-email: lazr-developers@lists.launchpad.net
  8. License: LGPL v3
  9. Download-URL: https://launchpad.net/wadllib/+download
  10. Platform: UNKNOWN
  11. Classifier: Development Status :: 5 - Production/Stable
  12. Classifier: Intended Audience :: Developers
  13. Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)
  14. Classifier: Operating System :: OS Independent
  15. Classifier: Programming Language :: Python
  16. Classifier: Programming Language :: Python :: 2
  17. Classifier: Programming Language :: Python :: 2.7
  18. Classifier: Programming Language :: Python :: 3
  19. Classifier: Programming Language :: Python :: 3.5
  20. Classifier: Programming Language :: Python :: 3.6
  21. Classifier: Programming Language :: Python :: 3.7
  22. Classifier: Programming Language :: Python :: 3.8
  23. Requires-Dist: lazr.uri
  24. Requires-Dist: setuptools
  25. Requires-Dist: importlib-metadata ; python_version < "3.8"
  26. Provides-Extra: docs
  27. Requires-Dist: Sphinx ; extra == 'docs'
  28. ..
  29. Copyright (C) 2008-2013 Canonical Ltd.
  30. This file is part of wadllib.
  31. wadllib is free software: you can redistribute it and/or modify it under
  32. the terms of the GNU Lesser General Public License as published by the
  33. Free Software Foundation, version 3 of the License.
  34. wadllib is distributed in the hope that it will be useful, but WITHOUT ANY
  35. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  36. FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
  37. more details.
  38. You should have received a copy of the GNU Lesser General Public License
  39. along with wadllib. If not, see <http://www.gnu.org/licenses/>.
  40. =======
  41. wadllib
  42. =======
  43. An Application object represents a web service described by a WADL
  44. file.
  45. >>> import os
  46. >>> import sys
  47. >>> import pkg_resources
  48. >>> from wadllib.application import Application
  49. The first argument to the Application constructor is the URL at which
  50. the WADL file was found. The second argument may be raw WADL markup.
  51. >>> wadl_string = pkg_resources.resource_string(
  52. ... 'wadllib.tests.data', 'launchpad-wadl.xml')
  53. >>> wadl = Application("http://api.launchpad.dev/beta/", wadl_string)
  54. Or the second argument may be an open filehandle containing the markup.
  55. >>> cleanups = []
  56. >>> def application_for(filename, url="http://www.example.com/"):
  57. ... wadl_stream = pkg_resources.resource_stream(
  58. ... 'wadllib.tests.data', filename)
  59. ... cleanups.append(wadl_stream)
  60. ... return Application(url, wadl_stream)
  61. >>> wadl = application_for("launchpad-wadl.xml",
  62. ... "http://api.launchpad.dev/beta/")
  63. Link navigation
  64. ===============
  65. The preferred technique for finding a resource is to start at one of
  66. the resources defined in the WADL file, and follow links. This code
  67. retrieves the definition of the root resource.
  68. >>> service_root = wadl.get_resource_by_path('')
  69. >>> service_root.url
  70. 'http://api.launchpad.dev/beta/'
  71. >>> service_root.type_url
  72. '#service-root'
  73. The service root resource supports GET.
  74. >>> get_method = service_root.get_method('get')
  75. >>> get_method.id
  76. 'service-root-get'
  77. >>> get_method = service_root.get_method('GET')
  78. >>> get_method.id
  79. 'service-root-get'
  80. If we want to invoke this method, we send a GET request to the service
  81. root URL.
  82. >>> get_method.name
  83. 'get'
  84. >>> get_method.build_request_url()
  85. 'http://api.launchpad.dev/beta/'
  86. The WADL description of a resource knows which representations are
  87. available for that resource. In this case, the server root resource
  88. has a a JSON representation, and it defines parameters like
  89. 'people_collection_link', a link to a list of people in Launchpad. We
  90. should be able to use the get_parameter() method to get the WADL
  91. definition of the 'people_collection_link' parameter and find out more
  92. about it--for instance, is it a link to another resource?
  93. >>> def test_raises(exc_class, method, *args, **kwargs):
  94. ... try:
  95. ... method(*args, **kwargs)
  96. ... except Exception:
  97. ... # Contortion to support Python < 2.6 and >= 3 simultaneously.
  98. ... e = sys.exc_info()[1]
  99. ... if isinstance(e, exc_class):
  100. ... print(e)
  101. ... return
  102. ... raise
  103. ... raise Exception("Expected exception %s not raised" % exc_class)
  104. >>> from wadllib.application import NoBoundRepresentationError
  105. >>> link_name = 'people_collection_link'
  106. >>> test_raises(
  107. ... NoBoundRepresentationError, service_root.get_parameter, link_name)
  108. Resource is not bound to any representation, and no media media type was specified.
  109. Oops. The code has no way to know whether 'people_collection_link' is
  110. a parameter of the JSON representation or some other kind of
  111. representation. We can pass a media type to get_parameter and let it
  112. know which representation the parameter lives in.
  113. >>> link_parameter = service_root.get_parameter(
  114. ... link_name, 'application/json')
  115. >>> test_raises(NoBoundRepresentationError, link_parameter.get_value)
  116. Resource is not bound to any representation.
  117. Oops again. The parameter is available, but it has no value, because
  118. there's no actual data associated with the resource. The browser can
  119. look up the description of the GET method to make an actual GET
  120. request to the service root, and bind the resulting representation to
  121. the WADL description of the service root.
  122. You can't bind just any representation to a WADL resource description.
  123. It has to be of a media type understood by the WADL description.
  124. >>> from wadllib.application import UnsupportedMediaTypeError
  125. >>> test_raises(
  126. ... UnsupportedMediaTypeError, service_root.bind,
  127. ... '<html>Some HTML</html>', 'text/html')
  128. This resource doesn't define a representation for media type text/html
  129. The WADL description of the service root resource has a JSON
  130. representation. Here it is.
  131. >>> json_representation = service_root.get_representation_definition(
  132. ... 'application/json')
  133. >>> json_representation.media_type
  134. 'application/json'
  135. We already have a WADL representation of the service root resource, so
  136. let's try binding it to that JSON representation. We use test JSON
  137. data from a file to simulate the result of a GET request to the
  138. service root.
  139. >>> def get_testdata(filename):
  140. ... return pkg_resources.resource_string(
  141. ... 'wadllib.tests.data', filename + '.json')
  142. >>> def bind_to_testdata(resource, filename):
  143. ... return resource.bind(get_testdata(filename), 'application/json')
  144. The return value is a new Resource object that's "bound" to that JSON
  145. test data.
  146. >>> bound_service_root = bind_to_testdata(service_root, 'root')
  147. >>> sorted([param.name for param in bound_service_root.parameters()])
  148. ['bugs_collection_link', 'people_collection_link']
  149. >>> sorted(bound_service_root.parameter_names())
  150. ['bugs_collection_link', 'people_collection_link']
  151. >>> [method.id for method in bound_service_root.method_iter]
  152. ['service-root-get']
  153. Now the bound resource object has a JSON representation, and now
  154. 'people_collection_link' makes sense. We can follow the
  155. 'people_collection_link' to a new Resource object.
  156. >>> link_parameter = bound_service_root.get_parameter(link_name)
  157. >>> link_parameter.style
  158. 'plain'
  159. >>> print(link_parameter.get_value())
  160. http://api.launchpad.dev/beta/people
  161. >>> personset_resource = link_parameter.linked_resource
  162. >>> personset_resource.__class__
  163. <class 'wadllib.application.Resource'>
  164. >>> print(personset_resource.url)
  165. http://api.launchpad.dev/beta/people
  166. >>> personset_resource.type_url
  167. 'http://api.launchpad.dev/beta/#people'
  168. This new resource is a collection of people.
  169. >>> personset_resource.id
  170. 'people'
  171. The "collection of people" resource supports a standard GET request as
  172. well as a special GET and an overloaded POST. The get_method() method
  173. is used to retrieve WADL definitions of the possible HTTP requests you
  174. might make. Here's how to get the WADL definition of the standard GET
  175. request.
  176. >>> get_method = personset_resource.get_method('get')
  177. >>> get_method.id
  178. 'people-get'
  179. The method name passed into get_method() is treated case-insensitively.
  180. >>> personset_resource.get_method('GET').id
  181. 'people-get'
  182. To invoke the special GET request, the client sets the 'ws.op' query
  183. parameter to the fixed string 'findPerson'.
  184. >>> find_method = personset_resource.get_method(
  185. ... query_params={'ws.op' : 'findPerson'})
  186. >>> find_method.id
  187. 'people-findPerson'
  188. Given an end-user's values for the non-fixed parameters, it's possible
  189. to get the URL that should be used to invoke the method.
  190. >>> print(find_method.build_request_url(text='foo'))
  191. http://api.launchpad.dev/beta/people?text=foo&ws.op=findPerson
  192. >>> print(find_method.build_request_url(
  193. ... {'ws.op' : 'findPerson', 'text' : 'bar'}))
  194. http://api.launchpad.dev/beta/people?text=bar&ws.op=findPerson
  195. An error occurs if the end-user gives an incorrect value for a fixed
  196. parameter value, or omits a required parameter.
  197. >>> find_method.build_request_url()
  198. Traceback (most recent call last):
  199. ...
  200. ValueError: No value for required parameter 'text'
  201. >>> find_method.build_request_url(
  202. ... {'ws.op' : 'findAPerson', 'text' : 'foo'})
  203. ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
  204. Traceback (most recent call last):
  205. ...
  206. ValueError: Value 'findAPerson' for parameter 'ws.op' conflicts
  207. with fixed value 'findPerson'
  208. To invoke the overloaded POST request, the client sets the 'ws.op'
  209. query variable to the fixed string 'newTeam':
  210. >>> create_team_method = personset_resource.get_method(
  211. ... 'post', representation_params={'ws.op' : 'newTeam'})
  212. >>> create_team_method.id
  213. 'people-newTeam'
  214. findMethod() returns None when there's no WADL method matching the
  215. name or the fixed parameters.
  216. >>> print(personset_resource.get_method('nosuchmethod'))
  217. None
  218. >>> print(personset_resource.get_method(
  219. ... 'post', query_params={'ws_op' : 'nosuchparam'}))
  220. None
  221. Let's say the browser makes a GET request to the person set resource
  222. and gets back a representation. We can bind that representation to our
  223. description of the person set resource.
  224. >>> bound_personset = bind_to_testdata(personset_resource, 'personset')
  225. >>> bound_personset.get_parameter("start").get_value()
  226. 0
  227. >>> bound_personset.get_parameter("total_size").get_value()
  228. 63
  229. We can keep following links indefinitely, so long as we bind to a
  230. representation to each resource as we get it, and use the
  231. representation to find the next link.
  232. >>> next_page_link = bound_personset.get_parameter("next_collection_link")
  233. >>> print(next_page_link.get_value())
  234. http://api.launchpad.dev/beta/people?ws.start=5&ws.size=5
  235. >>> page_two = next_page_link.linked_resource
  236. >>> bound_page_two = bind_to_testdata(page_two, 'personset-page2')
  237. >>> print(bound_page_two.url)
  238. http://api.launchpad.dev/beta/people?ws.start=5&ws.size=5
  239. >>> bound_page_two.get_parameter("start").get_value()
  240. 5
  241. >>> print(bound_page_two.get_parameter("next_collection_link").get_value())
  242. http://api.launchpad.dev/beta/people?ws.start=10&ws.size=5
  243. Let's say the browser makes a POST request that invokes the 'newTeam'
  244. named operation. The response will include a number of HTTP headers,
  245. including 'Location', which points the way to the newly created team.
  246. >>> headers = { 'Location' : 'http://api.launchpad.dev/~newteam' }
  247. >>> response = create_team_method.response.bind(headers)
  248. >>> location_parameter = response.get_parameter('Location')
  249. >>> location_parameter.get_value()
  250. 'http://api.launchpad.dev/~newteam'
  251. >>> new_team = location_parameter.linked_resource
  252. >>> new_team.url
  253. 'http://api.launchpad.dev/~newteam'
  254. >>> new_team.type_url
  255. 'http://api.launchpad.dev/beta/#team'
  256. Examining links
  257. ---------------
  258. The 'linked_resource' property of a parameter lets you follow a link
  259. to another object. The 'link' property of a parameter lets you examine
  260. links before following them.
  261. >>> import json
  262. >>> links_wadl = application_for('links-wadl.xml')
  263. >>> service_root = links_wadl.get_resource_by_path('')
  264. >>> representation = json.dumps(
  265. ... {'scalar_value': 'foo',
  266. ... 'known_link': 'http://known/',
  267. ... 'unknown_link': 'http://unknown/'})
  268. >>> bound_root = service_root.bind(representation)
  269. >>> print(bound_root.get_parameter("scalar_value").link)
  270. None
  271. >>> known_resource = bound_root.get_parameter("known_link")
  272. >>> unknown_resource = bound_root.get_parameter("unknown_link")
  273. >>> print(known_resource.link.can_follow)
  274. True
  275. >>> print(unknown_resource.link.can_follow)
  276. False
  277. A link whose type is unknown is a link to a resource not described by
  278. WADL. Following this link using .linked_resource or .link.follow will
  279. cause a wadllib error. You'll need to follow the link using a general
  280. HTTP library or some other tool.
  281. >>> known_resource.link.follow
  282. <wadllib.application.Resource object ...>
  283. >>> known_resource.linked_resource
  284. <wadllib.application.Resource object ...>
  285. >>> from wadllib.application import WADLError
  286. >>> test_raises(WADLError, getattr, unknown_resource.link, 'follow')
  287. Cannot follow a link when the target has no WADL
  288. description. Try using a general HTTP client instead.
  289. >>> test_raises(WADLError, getattr, unknown_resource, 'linked_resource')
  290. Cannot follow a link when the target has no WADL
  291. description. Try using a general HTTP client instead.
  292. Creating a Resource from a representation definition
  293. ====================================================
  294. Although every representation is a representation of some HTTP
  295. resource, an HTTP resource doesn't necessarily correspond directly to
  296. a WADL <resource> or <resource_type> tag. Sometimes a representation
  297. is defined within a WADL <method> tag.
  298. >>> find_method = personset_resource.get_method(
  299. ... query_params={'ws.op' : 'find'})
  300. >>> find_method.id
  301. 'people-find'
  302. >>> representation_definition = (
  303. ... find_method.response.get_representation_definition(
  304. ... 'application/json'))
  305. There may be no WADL <resource> or <resource_type> tag for the
  306. representation defined here. That's why wadllib makes it possible to
  307. instantiate an anonymous Resource object using only the representation
  308. definition.
  309. >>> from wadllib.application import Resource
  310. >>> anonymous_resource = Resource(
  311. ... wadl, "http://foo/", representation_definition.tag)
  312. We can bind this resource to a representation, as long as we
  313. explicitly pass in the representation definition.
  314. >>> anonymous_resource = anonymous_resource.bind(
  315. ... get_testdata('personset'), 'application/json',
  316. ... representation_definition=representation_definition)
  317. Once the resource is bound to a representation, we can get its
  318. parameter values.
  319. >>> print(anonymous_resource.get_parameter(
  320. ... 'total_size', 'application/json').get_value())
  321. 63
  322. Resource instantiation
  323. ======================
  324. If you happen to have the URL to an object lying around, and you know
  325. its type, you can construct a Resource object directly instead of
  326. by following links.
  327. >>> from wadllib.application import Resource
  328. >>> limi_person = Resource(wadl, "http://api.launchpad.dev/beta/~limi",
  329. ... "http://api.launchpad.dev/beta/#person")
  330. >>> sorted([method.id for method in limi_person.method_iter])[:3]
  331. ['person-acceptInvitationToBeMemberOf', 'person-addMember', 'person-declineInvitationToBeMemberOf']
  332. >>> bound_limi = bind_to_testdata(limi_person, 'person-limi')
  333. >>> sorted(bound_limi.parameter_names())[:3]
  334. ['admins_collection_link', 'confirmed_email_addresses_collection_link',
  335. 'date_created']
  336. >>> languages_link = bound_limi.get_parameter("languages_collection_link")
  337. >>> print(languages_link.get_value())
  338. http://api.launchpad.dev/beta/~limi/languages
  339. You can bind a Resource to a representation when you create it.
  340. >>> limi_data = get_testdata('person-limi')
  341. >>> bound_limi = Resource(
  342. ... wadl, "http://api.launchpad.dev/beta/~limi",
  343. ... "http://api.launchpad.dev/beta/#person", limi_data,
  344. ... "application/json")
  345. >>> print(bound_limi.get_parameter(
  346. ... "languages_collection_link").get_value())
  347. http://api.launchpad.dev/beta/~limi/languages
  348. By default the representation is treated as a string and processed
  349. according to the media type you pass into the Resource constructor. If
  350. you've already processed the representation, pass in False for the
  351. 'representation_needs_processing' argument.
  352. >>> from wadllib import _make_unicode
  353. >>> processed_limi_data = json.loads(_make_unicode(limi_data))
  354. >>> bound_limi = Resource(wadl, "http://api.launchpad.dev/beta/~limi",
  355. ... "http://api.launchpad.dev/beta/#person", processed_limi_data,
  356. ... "application/json", False)
  357. >>> print(bound_limi.get_parameter(
  358. ... "languages_collection_link").get_value())
  359. http://api.launchpad.dev/beta/~limi/languages
  360. Most of the time, the representation of a resource is of the type
  361. you'd get by sending a standard GET to that resource. If that's not
  362. the case, you can specify a RepresentationDefinition as the
  363. 'representation_definition' argument to bind() or the Resource
  364. constructor, to show what the representation really looks like. Here's
  365. an example.
  366. There's a method on a person resource such as bound_limi that's
  367. identified by a distinctive query argument: ws.op=getMembersByStatus.
  368. >>> method = bound_limi.get_method(
  369. ... query_params={'ws.op' : 'findPathToTeam'})
  370. Invoke this method with a GET request and you'll get back a page from
  371. a list of people.
  372. >>> people_page_repr_definition = (
  373. ... method.response.get_representation_definition('application/json'))
  374. >>> people_page_repr_definition.tag.attrib['href']
  375. 'http://api.launchpad.dev/beta/#person-page'
  376. As it happens, we have a page from a list of people to use as test data.
  377. >>> people_page_repr = get_testdata('personset')
  378. If we bind the resource to the result of the method invocation as
  379. happened above, we don't be able to access any of the parameters we'd
  380. expect. wadllib will think the representation is of type
  381. 'person-full', the default GET type for bound_limi.
  382. >>> bad_people_page = bound_limi.bind(people_page_repr)
  383. >>> print(bad_people_page.get_parameter('total_size'))
  384. None
  385. Since we don't actually have a 'person-full' representation, we won't
  386. be able to get values for the parameters of that kind of
  387. representation.
  388. >>> bad_people_page.get_parameter('name').get_value()
  389. Traceback (most recent call last):
  390. ...
  391. KeyError: 'name'
  392. So that's a dead end. *But*, if we pass the correct representation
  393. type into bind(), we can access the parameters associated with a
  394. 'person-page' representation.
  395. >>> people_page = bound_limi.bind(
  396. ... people_page_repr,
  397. ... representation_definition=people_page_repr_definition)
  398. >>> people_page.get_parameter('total_size').get_value()
  399. 63
  400. If you invoke the method and ask for a media type other than JSON, you
  401. won't get anything.
  402. >>> print(method.response.get_representation_definition('text/html'))
  403. None
  404. Data type conversion
  405. --------------------
  406. The values of date and dateTime parameters are automatically converted to
  407. Python datetime objects.
  408. >>> data_type_wadl = application_for('data-types-wadl.xml')
  409. >>> service_root = data_type_wadl.get_resource_by_path('')
  410. >>> representation = json.dumps(
  411. ... {'a_date': '2007-10-20',
  412. ... 'a_datetime': '2005-06-06T08:59:51.619713+00:00'})
  413. >>> bound_root = service_root.bind(representation, 'application/json')
  414. >>> bound_root.get_parameter('a_date').get_value()
  415. datetime.datetime(2007, 10, 20, 0, 0)
  416. >>> bound_root.get_parameter('a_datetime').get_value()
  417. datetime.datetime(2005, 6, 6, 8, ...)
  418. A 'date' field can include a timestamp, and a 'datetime' field can
  419. omit one. wadllib will turn both into datetime objects.
  420. >>> representation = json.dumps(
  421. ... {'a_date': '2005-06-06T08:59:51.619713+00:00',
  422. ... 'a_datetime': '2007-10-20'})
  423. >>> bound_root = service_root.bind(representation, 'application/json')
  424. >>> bound_root.get_parameter('a_datetime').get_value()
  425. datetime.datetime(2007, 10, 20, 0, 0)
  426. >>> bound_root.get_parameter('a_date').get_value()
  427. datetime.datetime(2005, 6, 6, 8, ...)
  428. If a date or dateTime parameter has a null value, you get None. If the
  429. value is a string that can't be parsed to a datetime object, you get a
  430. ValueError.
  431. >>> representation = json.dumps(
  432. ... {'a_date': 'foo', 'a_datetime': None})
  433. >>> bound_root = service_root.bind(representation, 'application/json')
  434. >>> bound_root.get_parameter('a_date').get_value()
  435. Traceback (most recent call last):
  436. ...
  437. ValueError: foo
  438. >>> print(bound_root.get_parameter('a_datetime').get_value())
  439. None
  440. Representation creation
  441. =======================
  442. You must provide a representation when invoking certain methods. The
  443. representation() method helps you build one without knowing the
  444. details of how a representation is put together.
  445. >>> create_team_method.build_representation(
  446. ... display_name='Joe Bloggs', name='joebloggs')
  447. ('application/x-www-form-urlencoded', 'display_name=Joe+Bloggs&name=joebloggs&ws.op=newTeam')
  448. The return value of build_representation is a 2-tuple containing the
  449. media type of the built representation, and the string representation
  450. itself. Along with the resource's URL, this is all you need to send
  451. the representation to a web server.
  452. >>> bound_limi.get_method('patch').build_representation(name='limi2')
  453. ('application/json', '{"name": "limi2"}')
  454. Representations may require values for certain parameters.
  455. >>> create_team_method.build_representation()
  456. Traceback (most recent call last):
  457. ...
  458. ValueError: No value for required parameter 'display_name'
  459. >>> bound_limi.get_method('put').build_representation(name='limi2')
  460. Traceback (most recent call last):
  461. ...
  462. ValueError: No value for required parameter 'mugshot_link'
  463. Some representations may safely include binary data.
  464. >>> binary_stream = pkg_resources.resource_stream(
  465. ... 'wadllib.tests.data', 'multipart-binary-wadl.xml')
  466. >>> cleanups.append(binary_stream)
  467. >>> binary_wadl = Application(
  468. ... "http://www.example.com/", binary_stream)
  469. >>> service_root = binary_wadl.get_resource_by_path('')
  470. Define a helper that processes the representation the same way
  471. zope.publisher would.
  472. >>> import cgi
  473. >>> import io
  474. >>> def assert_message_parts(media_type, doc, expected):
  475. ... environ = {
  476. ... 'REQUEST_METHOD': 'POST',
  477. ... 'CONTENT_TYPE': media_type,
  478. ... 'CONTENT_LENGTH': str(len(doc)),
  479. ... }
  480. ... kwargs = (
  481. ... {'encoding': 'UTF-8'} if sys.version_info[0] >= 3 else {})
  482. ... fs = cgi.FieldStorage(
  483. ... fp=io.BytesIO(doc), environ=environ, keep_blank_values=1,
  484. ... **kwargs)
  485. ... values = []
  486. ... def append_values(fields):
  487. ... for field in fields:
  488. ... if field.list:
  489. ... append_values(field.list)
  490. ... else:
  491. ... values.append(field.value)
  492. ... append_values(fs.list)
  493. ... assert values == expected, (
  494. ... 'Expected %s, got %s' % (expected, values))
  495. >>> method = service_root.get_method('post', 'multipart/form-data')
  496. >>> media_type, doc = method.build_representation(
  497. ... text_field="text", binary_field=b"\x01\x02\r\x81\r")
  498. >>> print(media_type)
  499. multipart/form-data; boundary=...
  500. >>> assert_message_parts(media_type, doc, ['text', b'\x01\x02\r\x81\r'])
  501. >>> method = service_root.get_method('post', 'multipart/form-data')
  502. >>> media_type, doc = method.build_representation(
  503. ... text_field=u"text", binary_field=b"\x01\x02\r\x81\r")
  504. >>> print(media_type)
  505. multipart/form-data; boundary=...
  506. >>> assert_message_parts(media_type, doc, ['text', b'\x01\x02\r\x81\r'])
  507. >>> method = service_root.get_method('post', 'multipart/form-data')
  508. >>> media_type, doc = method.build_representation(
  509. ... text_field="text\n", binary_field=b"\x01\x02\r\x81\n\r")
  510. >>> print(media_type)
  511. multipart/form-data; boundary=...
  512. >>> assert_message_parts(
  513. ... media_type, doc, ['text\r\n', b'\x01\x02\r\x81\n\r'])
  514. >>> method = service_root.get_method('post', 'multipart/form-data')
  515. >>> media_type, doc = method.build_representation(
  516. ... text_field=u"text\n", binary_field=b"\x01\x02\r\x81\n\r")
  517. >>> print(media_type)
  518. multipart/form-data; boundary=...
  519. >>> assert_message_parts(
  520. ... media_type, doc, ['text\r\n', b'\x01\x02\r\x81\n\r'])
  521. >>> method = service_root.get_method('post', 'multipart/form-data')
  522. >>> media_type, doc = method.build_representation(
  523. ... text_field="text\r\nmore\r\n",
  524. ... binary_field=b"\x01\x02\r\n\x81\r\x82\n")
  525. >>> print(media_type)
  526. multipart/form-data; boundary=...
  527. >>> assert_message_parts(
  528. ... media_type, doc, ['text\r\nmore\r\n', b'\x01\x02\r\n\x81\r\x82\n'])
  529. >>> method = service_root.get_method('post', 'multipart/form-data')
  530. >>> media_type, doc = method.build_representation(
  531. ... text_field=u"text\r\nmore\r\n",
  532. ... binary_field=b"\x01\x02\r\n\x81\r\x82\n")
  533. >>> print(media_type)
  534. multipart/form-data; boundary=...
  535. >>> assert_message_parts(
  536. ... media_type, doc, ['text\r\nmore\r\n', b'\x01\x02\r\n\x81\r\x82\n'])
  537. >>> method = service_root.get_method('post', 'text/unknown')
  538. >>> method.build_representation(field="value")
  539. Traceback (most recent call last):
  540. ...
  541. ValueError: Unsupported media type: 'text/unknown'
  542. Options
  543. =======
  544. Some parameters take values from a predefined list of options.
  545. >>> option_wadl = application_for('options-wadl.xml')
  546. >>> definitions = option_wadl.representation_definitions
  547. >>> service_root = option_wadl.get_resource_by_path('')
  548. >>> definition = definitions['service-root-json']
  549. >>> param = definition.params(service_root)[0]
  550. >>> print(param.name)
  551. has_options
  552. >>> sorted([option.value for option in param.options])
  553. ['Value 1', 'Value 2']
  554. Such parameters cannot take values that are not in the list.
  555. >>> definition.validate_param_values(
  556. ... [param], {'has_options': 'Value 1'})
  557. {'has_options': 'Value 1'}
  558. >>> definition.validate_param_values(
  559. ... [param], {'has_options': 'Invalid value'})
  560. Traceback (most recent call last):
  561. ...
  562. ValueError: Invalid value 'Invalid value' for parameter
  563. 'has_options': valid values are: "Value 1", "Value 2"
  564. Error conditions
  565. ================
  566. You'll get None if you try to look up a nonexistent resource.
  567. >>> print(wadl.get_resource_by_path('nosuchresource'))
  568. None
  569. You'll get an exception if you try to look up a nonexistent resource
  570. type.
  571. >>> print(wadl.get_resource_type('#nosuchtype'))
  572. Traceback (most recent call last):
  573. KeyError: 'No such XML ID: "#nosuchtype"'
  574. You'll get None if you try to look up a method whose parameters don't
  575. match any defined method.
  576. >>> print(bound_limi.get_method(
  577. ... 'post', representation_params={ 'foo' : 'bar' }))
  578. None
  579. .. cleanup
  580. >>> for stream in cleanups:
  581. ... stream.close()
  582. ================
  583. NEWS for wadllib
  584. ================
  585. 1.3.6 (2021-09-13)
  586. ==================
  587. - Remove buildout support in favour of tox. [bug=922605]
  588. - Adjust versioning strategy to avoid importing pkg_resources, which is slow
  589. in large environments.
  590. 1.3.5 (2021-01-20)
  591. ==================
  592. - Drop support for Python 3.2, 3.3, and 3.4.
  593. - Accept Unicode parameter values again when performing multipart/form-data
  594. encoding on Python 2 (broken in 1.3.3).
  595. 1.3.4 (2020-04-29)
  596. ==================
  597. - Advertise support for Python 3.8.
  598. - Add Python 3.9 compatibility by using xml.etree.ElementTree if
  599. xml.etree.cElementTree does not exist. [bug=1870294]
  600. 1.3.3 (2018-07-20)
  601. ==================
  602. - Drop support for Python < 2.6.
  603. - Add tox testing support.
  604. - Implement a subset of MIME multipart/form-data encoding locally rather
  605. than using the standard library's email module, which doesn't have good
  606. handling of binary parts and corrupts bytes in them that look like line
  607. endings in various ways depending on the Python version. [bug=1729754]
  608. 1.3.2 (2013-02-25)
  609. ==================
  610. - Impose sort order to avoid test failures due to hash randomization.
  611. LP: #1132125
  612. - Be sure to close streams opened by pkg_resources.resource_stream() to avoid
  613. test suite complaints.
  614. 1.3.1 (2012-03-22)
  615. ==================
  616. - Correct the double pass through _from_string causing datetime issues
  617. 1.3.0 (2012-01-27)
  618. ==================
  619. - Add Python 3 compatibility
  620. - Add the ability to inspect links before following them.
  621. - Ensure that the sample data is packaged.
  622. 1.2.0 (2011-02-03)
  623. ==================
  624. - It's now possible to examine a link before following it, to see
  625. whether it has a WADL description or whether it needs to be fetched
  626. with a general HTTP client.
  627. - It's now possible to iterate over a resource's Parameter objects
  628. with the .parameters() method.
  629. 1.1.8 (2010-10-27)
  630. ==================
  631. - This revision contains no code changes, but the build system was
  632. changed (yet again). This time to include the version.txt file
  633. used by setup.py.
  634. 1.1.7 (2010-10-26)
  635. ==================
  636. - This revision contains no code changes, but the build system was
  637. changed (again) to include the sample data used in tests.
  638. 1.1.6 (2010-10-21)
  639. ==================
  640. - This revision contains no code changes, but the build system was
  641. changed to include the sample data used in tests.
  642. 1.1.5 (2010-05-04)
  643. ==================
  644. - Fixed a bug (Launchpad bug 274074) that prevented the lookup of
  645. parameter values in resources associated directly with a
  646. representation definition (rather than a resource type with a
  647. representation definition). Bug fix provided by James Westby.
  648. 1.1.4 (2009-09-15)
  649. ==================
  650. - Fixed a bug that crashed wadllib unless all parameters of a
  651. multipart representation were provided.
  652. 1.1.3 (2009-08-26)
  653. ==================
  654. - Remove unnecessary build dependencies.
  655. - Add missing dependencies to setup file.
  656. - Remove sys.path hack from setup.py.
  657. 1.1.2 (2009-08-20)
  658. ==================
  659. - Consistently handle different versions of simplejson.
  660. 1.1.1 (2009-07-14)
  661. ==================
  662. - Make wadllib aware of the <option> tags that go beneath <param> tags.
  663. 1.1 (2009-07-09)
  664. ================
  665. - Make wadllib capable of recognizing and generating
  666. multipart/form-data representations, including representations that
  667. incorporate binary parameters.
  668. 1.0 (2009-03-23)
  669. ================
  670. - Initial release on PyPI