index.rst 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. ..
  2. Copyright (C) 2008-2013 Canonical Ltd.
  3. This file is part of wadllib.
  4. wadllib is free software: you can redistribute it and/or modify it under
  5. the terms of the GNU Lesser General Public License as published by the
  6. Free Software Foundation, version 3 of the License.
  7. wadllib is distributed in the hope that it will be useful, but WITHOUT ANY
  8. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
  10. more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with wadllib. If not, see <http://www.gnu.org/licenses/>.
  13. =======
  14. wadllib
  15. =======
  16. An Application object represents a web service described by a WADL
  17. file.
  18. >>> import os
  19. >>> import sys
  20. >>> import pkg_resources
  21. >>> from wadllib.application import Application
  22. The first argument to the Application constructor is the URL at which
  23. the WADL file was found. The second argument may be raw WADL markup.
  24. >>> wadl_string = pkg_resources.resource_string(
  25. ... 'wadllib.tests.data', 'launchpad-wadl.xml')
  26. >>> wadl = Application("http://api.launchpad.dev/beta/", wadl_string)
  27. Or the second argument may be an open filehandle containing the markup.
  28. >>> cleanups = []
  29. >>> def application_for(filename, url="http://www.example.com/"):
  30. ... wadl_stream = pkg_resources.resource_stream(
  31. ... 'wadllib.tests.data', filename)
  32. ... cleanups.append(wadl_stream)
  33. ... return Application(url, wadl_stream)
  34. >>> wadl = application_for("launchpad-wadl.xml",
  35. ... "http://api.launchpad.dev/beta/")
  36. Link navigation
  37. ===============
  38. The preferred technique for finding a resource is to start at one of
  39. the resources defined in the WADL file, and follow links. This code
  40. retrieves the definition of the root resource.
  41. >>> service_root = wadl.get_resource_by_path('')
  42. >>> service_root.url
  43. 'http://api.launchpad.dev/beta/'
  44. >>> service_root.type_url
  45. '#service-root'
  46. The service root resource supports GET.
  47. >>> get_method = service_root.get_method('get')
  48. >>> get_method.id
  49. 'service-root-get'
  50. >>> get_method = service_root.get_method('GET')
  51. >>> get_method.id
  52. 'service-root-get'
  53. If we want to invoke this method, we send a GET request to the service
  54. root URL.
  55. >>> get_method.name
  56. 'get'
  57. >>> get_method.build_request_url()
  58. 'http://api.launchpad.dev/beta/'
  59. The WADL description of a resource knows which representations are
  60. available for that resource. In this case, the server root resource
  61. has a a JSON representation, and it defines parameters like
  62. 'people_collection_link', a link to a list of people in Launchpad. We
  63. should be able to use the get_parameter() method to get the WADL
  64. definition of the 'people_collection_link' parameter and find out more
  65. about it--for instance, is it a link to another resource?
  66. >>> def test_raises(exc_class, method, *args, **kwargs):
  67. ... try:
  68. ... method(*args, **kwargs)
  69. ... except Exception:
  70. ... # Contortion to support Python < 2.6 and >= 3 simultaneously.
  71. ... e = sys.exc_info()[1]
  72. ... if isinstance(e, exc_class):
  73. ... print(e)
  74. ... return
  75. ... raise
  76. ... raise Exception("Expected exception %s not raised" % exc_class)
  77. >>> from wadllib.application import NoBoundRepresentationError
  78. >>> link_name = 'people_collection_link'
  79. >>> test_raises(
  80. ... NoBoundRepresentationError, service_root.get_parameter, link_name)
  81. Resource is not bound to any representation, and no media media type was specified.
  82. Oops. The code has no way to know whether 'people_collection_link' is
  83. a parameter of the JSON representation or some other kind of
  84. representation. We can pass a media type to get_parameter and let it
  85. know which representation the parameter lives in.
  86. >>> link_parameter = service_root.get_parameter(
  87. ... link_name, 'application/json')
  88. >>> test_raises(NoBoundRepresentationError, link_parameter.get_value)
  89. Resource is not bound to any representation.
  90. Oops again. The parameter is available, but it has no value, because
  91. there's no actual data associated with the resource. The browser can
  92. look up the description of the GET method to make an actual GET
  93. request to the service root, and bind the resulting representation to
  94. the WADL description of the service root.
  95. You can't bind just any representation to a WADL resource description.
  96. It has to be of a media type understood by the WADL description.
  97. >>> from wadllib.application import UnsupportedMediaTypeError
  98. >>> test_raises(
  99. ... UnsupportedMediaTypeError, service_root.bind,
  100. ... '<html>Some HTML</html>', 'text/html')
  101. This resource doesn't define a representation for media type text/html
  102. The WADL description of the service root resource has a JSON
  103. representation. Here it is.
  104. >>> json_representation = service_root.get_representation_definition(
  105. ... 'application/json')
  106. >>> json_representation.media_type
  107. 'application/json'
  108. We already have a WADL representation of the service root resource, so
  109. let's try binding it to that JSON representation. We use test JSON
  110. data from a file to simulate the result of a GET request to the
  111. service root.
  112. >>> def get_testdata(filename):
  113. ... return pkg_resources.resource_string(
  114. ... 'wadllib.tests.data', filename + '.json')
  115. >>> def bind_to_testdata(resource, filename):
  116. ... return resource.bind(get_testdata(filename), 'application/json')
  117. The return value is a new Resource object that's "bound" to that JSON
  118. test data.
  119. >>> bound_service_root = bind_to_testdata(service_root, 'root')
  120. >>> sorted([param.name for param in bound_service_root.parameters()])
  121. ['bugs_collection_link', 'people_collection_link']
  122. >>> sorted(bound_service_root.parameter_names())
  123. ['bugs_collection_link', 'people_collection_link']
  124. >>> [method.id for method in bound_service_root.method_iter]
  125. ['service-root-get']
  126. Now the bound resource object has a JSON representation, and now
  127. 'people_collection_link' makes sense. We can follow the
  128. 'people_collection_link' to a new Resource object.
  129. >>> link_parameter = bound_service_root.get_parameter(link_name)
  130. >>> link_parameter.style
  131. 'plain'
  132. >>> print(link_parameter.get_value())
  133. http://api.launchpad.dev/beta/people
  134. >>> personset_resource = link_parameter.linked_resource
  135. >>> personset_resource.__class__
  136. <class 'wadllib.application.Resource'>
  137. >>> print(personset_resource.url)
  138. http://api.launchpad.dev/beta/people
  139. >>> personset_resource.type_url
  140. 'http://api.launchpad.dev/beta/#people'
  141. This new resource is a collection of people.
  142. >>> personset_resource.id
  143. 'people'
  144. The "collection of people" resource supports a standard GET request as
  145. well as a special GET and an overloaded POST. The get_method() method
  146. is used to retrieve WADL definitions of the possible HTTP requests you
  147. might make. Here's how to get the WADL definition of the standard GET
  148. request.
  149. >>> get_method = personset_resource.get_method('get')
  150. >>> get_method.id
  151. 'people-get'
  152. The method name passed into get_method() is treated case-insensitively.
  153. >>> personset_resource.get_method('GET').id
  154. 'people-get'
  155. To invoke the special GET request, the client sets the 'ws.op' query
  156. parameter to the fixed string 'findPerson'.
  157. >>> find_method = personset_resource.get_method(
  158. ... query_params={'ws.op' : 'findPerson'})
  159. >>> find_method.id
  160. 'people-findPerson'
  161. Given an end-user's values for the non-fixed parameters, it's possible
  162. to get the URL that should be used to invoke the method.
  163. >>> print(find_method.build_request_url(text='foo'))
  164. http://api.launchpad.dev/beta/people?text=foo&ws.op=findPerson
  165. >>> print(find_method.build_request_url(
  166. ... {'ws.op' : 'findPerson', 'text' : 'bar'}))
  167. http://api.launchpad.dev/beta/people?text=bar&ws.op=findPerson
  168. An error occurs if the end-user gives an incorrect value for a fixed
  169. parameter value, or omits a required parameter.
  170. >>> find_method.build_request_url()
  171. Traceback (most recent call last):
  172. ...
  173. ValueError: No value for required parameter 'text'
  174. >>> find_method.build_request_url(
  175. ... {'ws.op' : 'findAPerson', 'text' : 'foo'})
  176. ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
  177. Traceback (most recent call last):
  178. ...
  179. ValueError: Value 'findAPerson' for parameter 'ws.op' conflicts
  180. with fixed value 'findPerson'
  181. To invoke the overloaded POST request, the client sets the 'ws.op'
  182. query variable to the fixed string 'newTeam':
  183. >>> create_team_method = personset_resource.get_method(
  184. ... 'post', representation_params={'ws.op' : 'newTeam'})
  185. >>> create_team_method.id
  186. 'people-newTeam'
  187. findMethod() returns None when there's no WADL method matching the
  188. name or the fixed parameters.
  189. >>> print(personset_resource.get_method('nosuchmethod'))
  190. None
  191. >>> print(personset_resource.get_method(
  192. ... 'post', query_params={'ws_op' : 'nosuchparam'}))
  193. None
  194. Let's say the browser makes a GET request to the person set resource
  195. and gets back a representation. We can bind that representation to our
  196. description of the person set resource.
  197. >>> bound_personset = bind_to_testdata(personset_resource, 'personset')
  198. >>> bound_personset.get_parameter("start").get_value()
  199. 0
  200. >>> bound_personset.get_parameter("total_size").get_value()
  201. 63
  202. We can keep following links indefinitely, so long as we bind to a
  203. representation to each resource as we get it, and use the
  204. representation to find the next link.
  205. >>> next_page_link = bound_personset.get_parameter("next_collection_link")
  206. >>> print(next_page_link.get_value())
  207. http://api.launchpad.dev/beta/people?ws.start=5&ws.size=5
  208. >>> page_two = next_page_link.linked_resource
  209. >>> bound_page_two = bind_to_testdata(page_two, 'personset-page2')
  210. >>> print(bound_page_two.url)
  211. http://api.launchpad.dev/beta/people?ws.start=5&ws.size=5
  212. >>> bound_page_two.get_parameter("start").get_value()
  213. 5
  214. >>> print(bound_page_two.get_parameter("next_collection_link").get_value())
  215. http://api.launchpad.dev/beta/people?ws.start=10&ws.size=5
  216. Let's say the browser makes a POST request that invokes the 'newTeam'
  217. named operation. The response will include a number of HTTP headers,
  218. including 'Location', which points the way to the newly created team.
  219. >>> headers = { 'Location' : 'http://api.launchpad.dev/~newteam' }
  220. >>> response = create_team_method.response.bind(headers)
  221. >>> location_parameter = response.get_parameter('Location')
  222. >>> location_parameter.get_value()
  223. 'http://api.launchpad.dev/~newteam'
  224. >>> new_team = location_parameter.linked_resource
  225. >>> new_team.url
  226. 'http://api.launchpad.dev/~newteam'
  227. >>> new_team.type_url
  228. 'http://api.launchpad.dev/beta/#team'
  229. Examining links
  230. ---------------
  231. The 'linked_resource' property of a parameter lets you follow a link
  232. to another object. The 'link' property of a parameter lets you examine
  233. links before following them.
  234. >>> import json
  235. >>> links_wadl = application_for('links-wadl.xml')
  236. >>> service_root = links_wadl.get_resource_by_path('')
  237. >>> representation = json.dumps(
  238. ... {'scalar_value': 'foo',
  239. ... 'known_link': 'http://known/',
  240. ... 'unknown_link': 'http://unknown/'})
  241. >>> bound_root = service_root.bind(representation)
  242. >>> print(bound_root.get_parameter("scalar_value").link)
  243. None
  244. >>> known_resource = bound_root.get_parameter("known_link")
  245. >>> unknown_resource = bound_root.get_parameter("unknown_link")
  246. >>> print(known_resource.link.can_follow)
  247. True
  248. >>> print(unknown_resource.link.can_follow)
  249. False
  250. A link whose type is unknown is a link to a resource not described by
  251. WADL. Following this link using .linked_resource or .link.follow will
  252. cause a wadllib error. You'll need to follow the link using a general
  253. HTTP library or some other tool.
  254. >>> known_resource.link.follow
  255. <wadllib.application.Resource object ...>
  256. >>> known_resource.linked_resource
  257. <wadllib.application.Resource object ...>
  258. >>> from wadllib.application import WADLError
  259. >>> test_raises(WADLError, getattr, unknown_resource.link, 'follow')
  260. Cannot follow a link when the target has no WADL
  261. description. Try using a general HTTP client instead.
  262. >>> test_raises(WADLError, getattr, unknown_resource, 'linked_resource')
  263. Cannot follow a link when the target has no WADL
  264. description. Try using a general HTTP client instead.
  265. Creating a Resource from a representation definition
  266. ====================================================
  267. Although every representation is a representation of some HTTP
  268. resource, an HTTP resource doesn't necessarily correspond directly to
  269. a WADL <resource> or <resource_type> tag. Sometimes a representation
  270. is defined within a WADL <method> tag.
  271. >>> find_method = personset_resource.get_method(
  272. ... query_params={'ws.op' : 'find'})
  273. >>> find_method.id
  274. 'people-find'
  275. >>> representation_definition = (
  276. ... find_method.response.get_representation_definition(
  277. ... 'application/json'))
  278. There may be no WADL <resource> or <resource_type> tag for the
  279. representation defined here. That's why wadllib makes it possible to
  280. instantiate an anonymous Resource object using only the representation
  281. definition.
  282. >>> from wadllib.application import Resource
  283. >>> anonymous_resource = Resource(
  284. ... wadl, "http://foo/", representation_definition.tag)
  285. We can bind this resource to a representation, as long as we
  286. explicitly pass in the representation definition.
  287. >>> anonymous_resource = anonymous_resource.bind(
  288. ... get_testdata('personset'), 'application/json',
  289. ... representation_definition=representation_definition)
  290. Once the resource is bound to a representation, we can get its
  291. parameter values.
  292. >>> print(anonymous_resource.get_parameter(
  293. ... 'total_size', 'application/json').get_value())
  294. 63
  295. Resource instantiation
  296. ======================
  297. If you happen to have the URL to an object lying around, and you know
  298. its type, you can construct a Resource object directly instead of
  299. by following links.
  300. >>> from wadllib.application import Resource
  301. >>> limi_person = Resource(wadl, "http://api.launchpad.dev/beta/~limi",
  302. ... "http://api.launchpad.dev/beta/#person")
  303. >>> sorted([method.id for method in limi_person.method_iter])[:3]
  304. ['person-acceptInvitationToBeMemberOf', 'person-addMember', 'person-declineInvitationToBeMemberOf']
  305. >>> bound_limi = bind_to_testdata(limi_person, 'person-limi')
  306. >>> sorted(bound_limi.parameter_names())[:3]
  307. ['admins_collection_link', 'confirmed_email_addresses_collection_link',
  308. 'date_created']
  309. >>> languages_link = bound_limi.get_parameter("languages_collection_link")
  310. >>> print(languages_link.get_value())
  311. http://api.launchpad.dev/beta/~limi/languages
  312. You can bind a Resource to a representation when you create it.
  313. >>> limi_data = get_testdata('person-limi')
  314. >>> bound_limi = Resource(
  315. ... wadl, "http://api.launchpad.dev/beta/~limi",
  316. ... "http://api.launchpad.dev/beta/#person", limi_data,
  317. ... "application/json")
  318. >>> print(bound_limi.get_parameter(
  319. ... "languages_collection_link").get_value())
  320. http://api.launchpad.dev/beta/~limi/languages
  321. By default the representation is treated as a string and processed
  322. according to the media type you pass into the Resource constructor. If
  323. you've already processed the representation, pass in False for the
  324. 'representation_needs_processing' argument.
  325. >>> from wadllib import _make_unicode
  326. >>> processed_limi_data = json.loads(_make_unicode(limi_data))
  327. >>> bound_limi = Resource(wadl, "http://api.launchpad.dev/beta/~limi",
  328. ... "http://api.launchpad.dev/beta/#person", processed_limi_data,
  329. ... "application/json", False)
  330. >>> print(bound_limi.get_parameter(
  331. ... "languages_collection_link").get_value())
  332. http://api.launchpad.dev/beta/~limi/languages
  333. Most of the time, the representation of a resource is of the type
  334. you'd get by sending a standard GET to that resource. If that's not
  335. the case, you can specify a RepresentationDefinition as the
  336. 'representation_definition' argument to bind() or the Resource
  337. constructor, to show what the representation really looks like. Here's
  338. an example.
  339. There's a method on a person resource such as bound_limi that's
  340. identified by a distinctive query argument: ws.op=getMembersByStatus.
  341. >>> method = bound_limi.get_method(
  342. ... query_params={'ws.op' : 'findPathToTeam'})
  343. Invoke this method with a GET request and you'll get back a page from
  344. a list of people.
  345. >>> people_page_repr_definition = (
  346. ... method.response.get_representation_definition('application/json'))
  347. >>> people_page_repr_definition.tag.attrib['href']
  348. 'http://api.launchpad.dev/beta/#person-page'
  349. As it happens, we have a page from a list of people to use as test data.
  350. >>> people_page_repr = get_testdata('personset')
  351. If we bind the resource to the result of the method invocation as
  352. happened above, we don't be able to access any of the parameters we'd
  353. expect. wadllib will think the representation is of type
  354. 'person-full', the default GET type for bound_limi.
  355. >>> bad_people_page = bound_limi.bind(people_page_repr)
  356. >>> print(bad_people_page.get_parameter('total_size'))
  357. None
  358. Since we don't actually have a 'person-full' representation, we won't
  359. be able to get values for the parameters of that kind of
  360. representation.
  361. >>> bad_people_page.get_parameter('name').get_value()
  362. Traceback (most recent call last):
  363. ...
  364. KeyError: 'name'
  365. So that's a dead end. *But*, if we pass the correct representation
  366. type into bind(), we can access the parameters associated with a
  367. 'person-page' representation.
  368. >>> people_page = bound_limi.bind(
  369. ... people_page_repr,
  370. ... representation_definition=people_page_repr_definition)
  371. >>> people_page.get_parameter('total_size').get_value()
  372. 63
  373. If you invoke the method and ask for a media type other than JSON, you
  374. won't get anything.
  375. >>> print(method.response.get_representation_definition('text/html'))
  376. None
  377. Data type conversion
  378. --------------------
  379. The values of date and dateTime parameters are automatically converted to
  380. Python datetime objects.
  381. >>> data_type_wadl = application_for('data-types-wadl.xml')
  382. >>> service_root = data_type_wadl.get_resource_by_path('')
  383. >>> representation = json.dumps(
  384. ... {'a_date': '2007-10-20',
  385. ... 'a_datetime': '2005-06-06T08:59:51.619713+00:00'})
  386. >>> bound_root = service_root.bind(representation, 'application/json')
  387. >>> bound_root.get_parameter('a_date').get_value()
  388. datetime.datetime(2007, 10, 20, 0, 0)
  389. >>> bound_root.get_parameter('a_datetime').get_value()
  390. datetime.datetime(2005, 6, 6, 8, ...)
  391. A 'date' field can include a timestamp, and a 'datetime' field can
  392. omit one. wadllib will turn both into datetime objects.
  393. >>> representation = json.dumps(
  394. ... {'a_date': '2005-06-06T08:59:51.619713+00:00',
  395. ... 'a_datetime': '2007-10-20'})
  396. >>> bound_root = service_root.bind(representation, 'application/json')
  397. >>> bound_root.get_parameter('a_datetime').get_value()
  398. datetime.datetime(2007, 10, 20, 0, 0)
  399. >>> bound_root.get_parameter('a_date').get_value()
  400. datetime.datetime(2005, 6, 6, 8, ...)
  401. If a date or dateTime parameter has a null value, you get None. If the
  402. value is a string that can't be parsed to a datetime object, you get a
  403. ValueError.
  404. >>> representation = json.dumps(
  405. ... {'a_date': 'foo', 'a_datetime': None})
  406. >>> bound_root = service_root.bind(representation, 'application/json')
  407. >>> bound_root.get_parameter('a_date').get_value()
  408. Traceback (most recent call last):
  409. ...
  410. ValueError: foo
  411. >>> print(bound_root.get_parameter('a_datetime').get_value())
  412. None
  413. Representation creation
  414. =======================
  415. You must provide a representation when invoking certain methods. The
  416. representation() method helps you build one without knowing the
  417. details of how a representation is put together.
  418. >>> create_team_method.build_representation(
  419. ... display_name='Joe Bloggs', name='joebloggs')
  420. ('application/x-www-form-urlencoded', 'display_name=Joe+Bloggs&name=joebloggs&ws.op=newTeam')
  421. The return value of build_representation is a 2-tuple containing the
  422. media type of the built representation, and the string representation
  423. itself. Along with the resource's URL, this is all you need to send
  424. the representation to a web server.
  425. >>> bound_limi.get_method('patch').build_representation(name='limi2')
  426. ('application/json', '{"name": "limi2"}')
  427. Representations may require values for certain parameters.
  428. >>> create_team_method.build_representation()
  429. Traceback (most recent call last):
  430. ...
  431. ValueError: No value for required parameter 'display_name'
  432. >>> bound_limi.get_method('put').build_representation(name='limi2')
  433. Traceback (most recent call last):
  434. ...
  435. ValueError: No value for required parameter 'mugshot_link'
  436. Some representations may safely include binary data.
  437. >>> binary_stream = pkg_resources.resource_stream(
  438. ... 'wadllib.tests.data', 'multipart-binary-wadl.xml')
  439. >>> cleanups.append(binary_stream)
  440. >>> binary_wadl = Application(
  441. ... "http://www.example.com/", binary_stream)
  442. >>> service_root = binary_wadl.get_resource_by_path('')
  443. Define a helper that processes the representation the same way
  444. zope.publisher would.
  445. >>> import cgi
  446. >>> import io
  447. >>> def assert_message_parts(media_type, doc, expected):
  448. ... environ = {
  449. ... 'REQUEST_METHOD': 'POST',
  450. ... 'CONTENT_TYPE': media_type,
  451. ... 'CONTENT_LENGTH': str(len(doc)),
  452. ... }
  453. ... kwargs = (
  454. ... {'encoding': 'UTF-8'} if sys.version_info[0] >= 3 else {})
  455. ... fs = cgi.FieldStorage(
  456. ... fp=io.BytesIO(doc), environ=environ, keep_blank_values=1,
  457. ... **kwargs)
  458. ... values = []
  459. ... def append_values(fields):
  460. ... for field in fields:
  461. ... if field.list:
  462. ... append_values(field.list)
  463. ... else:
  464. ... values.append(field.value)
  465. ... append_values(fs.list)
  466. ... assert values == expected, (
  467. ... 'Expected %s, got %s' % (expected, values))
  468. >>> method = service_root.get_method('post', 'multipart/form-data')
  469. >>> media_type, doc = method.build_representation(
  470. ... text_field="text", binary_field=b"\x01\x02\r\x81\r")
  471. >>> print(media_type)
  472. multipart/form-data; boundary=...
  473. >>> assert_message_parts(media_type, doc, ['text', b'\x01\x02\r\x81\r'])
  474. >>> method = service_root.get_method('post', 'multipart/form-data')
  475. >>> media_type, doc = method.build_representation(
  476. ... text_field=u"text", binary_field=b"\x01\x02\r\x81\r")
  477. >>> print(media_type)
  478. multipart/form-data; boundary=...
  479. >>> assert_message_parts(media_type, doc, ['text', b'\x01\x02\r\x81\r'])
  480. >>> method = service_root.get_method('post', 'multipart/form-data')
  481. >>> media_type, doc = method.build_representation(
  482. ... text_field="text\n", binary_field=b"\x01\x02\r\x81\n\r")
  483. >>> print(media_type)
  484. multipart/form-data; boundary=...
  485. >>> assert_message_parts(
  486. ... media_type, doc, ['text\r\n', b'\x01\x02\r\x81\n\r'])
  487. >>> method = service_root.get_method('post', 'multipart/form-data')
  488. >>> media_type, doc = method.build_representation(
  489. ... text_field=u"text\n", binary_field=b"\x01\x02\r\x81\n\r")
  490. >>> print(media_type)
  491. multipart/form-data; boundary=...
  492. >>> assert_message_parts(
  493. ... media_type, doc, ['text\r\n', b'\x01\x02\r\x81\n\r'])
  494. >>> method = service_root.get_method('post', 'multipart/form-data')
  495. >>> media_type, doc = method.build_representation(
  496. ... text_field="text\r\nmore\r\n",
  497. ... binary_field=b"\x01\x02\r\n\x81\r\x82\n")
  498. >>> print(media_type)
  499. multipart/form-data; boundary=...
  500. >>> assert_message_parts(
  501. ... media_type, doc, ['text\r\nmore\r\n', b'\x01\x02\r\n\x81\r\x82\n'])
  502. >>> method = service_root.get_method('post', 'multipart/form-data')
  503. >>> media_type, doc = method.build_representation(
  504. ... text_field=u"text\r\nmore\r\n",
  505. ... binary_field=b"\x01\x02\r\n\x81\r\x82\n")
  506. >>> print(media_type)
  507. multipart/form-data; boundary=...
  508. >>> assert_message_parts(
  509. ... media_type, doc, ['text\r\nmore\r\n', b'\x01\x02\r\n\x81\r\x82\n'])
  510. >>> method = service_root.get_method('post', 'text/unknown')
  511. >>> method.build_representation(field="value")
  512. Traceback (most recent call last):
  513. ...
  514. ValueError: Unsupported media type: 'text/unknown'
  515. Options
  516. =======
  517. Some parameters take values from a predefined list of options.
  518. >>> option_wadl = application_for('options-wadl.xml')
  519. >>> definitions = option_wadl.representation_definitions
  520. >>> service_root = option_wadl.get_resource_by_path('')
  521. >>> definition = definitions['service-root-json']
  522. >>> param = definition.params(service_root)[0]
  523. >>> print(param.name)
  524. has_options
  525. >>> sorted([option.value for option in param.options])
  526. ['Value 1', 'Value 2']
  527. Such parameters cannot take values that are not in the list.
  528. >>> definition.validate_param_values(
  529. ... [param], {'has_options': 'Value 1'})
  530. {'has_options': 'Value 1'}
  531. >>> definition.validate_param_values(
  532. ... [param], {'has_options': 'Invalid value'})
  533. Traceback (most recent call last):
  534. ...
  535. ValueError: Invalid value 'Invalid value' for parameter
  536. 'has_options': valid values are: "Value 1", "Value 2"
  537. Error conditions
  538. ================
  539. You'll get None if you try to look up a nonexistent resource.
  540. >>> print(wadl.get_resource_by_path('nosuchresource'))
  541. None
  542. You'll get an exception if you try to look up a nonexistent resource
  543. type.
  544. >>> print(wadl.get_resource_type('#nosuchtype'))
  545. Traceback (most recent call last):
  546. KeyError: 'No such XML ID: "#nosuchtype"'
  547. You'll get None if you try to look up a method whose parameters don't
  548. match any defined method.
  549. >>> print(bound_limi.get_method(
  550. ... 'post', representation_params={ 'foo' : 'bar' }))
  551. None
  552. .. cleanup
  553. >>> for stream in cleanups:
  554. ... stream.close()
  555. .. pypi description ends here
  556. .. toctree::
  557. :glob:
  558. NEWS