application.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. # Copyright 2008-2018 Canonical Ltd. All rights reserved.
  2. # This file is part of wadllib.
  3. #
  4. # wadllib is free software: you can redistribute it and/or modify it under the
  5. # terms of the GNU Lesser General Public License as published by the Free
  6. # Software Foundation, version 3 of the License.
  7. #
  8. # wadllib is distributed in the hope that it will be useful, but WITHOUT ANY
  9. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  10. # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  11. # details.
  12. #
  13. # You should have received a copy of the GNU Lesser General Public License
  14. # along with wadllib. If not, see <http://www.gnu.org/licenses/>.
  15. """Navigate the resources exposed by a web service.
  16. The wadllib library helps a web client navigate the resources
  17. exposed by a web service. The service defines its resources in a
  18. single WADL file. wadllib parses this file and gives access to the
  19. resources defined inside. The client code can see the capabilities of
  20. a given resource and make the corresponding HTTP requests.
  21. If a request returns a representation of the resource, the client can
  22. bind the string representation to the wadllib Resource object.
  23. """
  24. __metaclass__ = type
  25. __all__ = [
  26. 'Application',
  27. 'Link',
  28. 'Method',
  29. 'NoBoundRepresentationError',
  30. 'Parameter',
  31. 'RepresentationDefinition',
  32. 'ResponseDefinition',
  33. 'Resource',
  34. 'ResourceType',
  35. 'WADLError',
  36. ]
  37. import datetime
  38. from email.utils import quote
  39. import io
  40. import json
  41. import random
  42. import re
  43. import sys
  44. import time
  45. try:
  46. from urllib.parse import urlencode
  47. except ImportError:
  48. from urllib import urlencode
  49. try:
  50. import xml.etree.cElementTree as ET
  51. except ImportError:
  52. import xml.etree.ElementTree as ET
  53. from lazr.uri import URI, merge
  54. from wadllib import (
  55. _make_unicode,
  56. _string_types,
  57. )
  58. from wadllib.iso_strptime import iso_strptime
  59. NS_MAP = "xmlns:map"
  60. XML_SCHEMA_NS_URI = 'http://www.w3.org/2001/XMLSchema'
  61. def wadl_tag(tag_name):
  62. """Scope a tag name with the WADL namespace."""
  63. return '{http://research.sun.com/wadl/2006/10}' + tag_name
  64. def wadl_xpath(tag_name):
  65. """Turn a tag name into an XPath path."""
  66. return './' + wadl_tag(tag_name)
  67. def _merge_dicts(*dicts):
  68. """Merge any number of dictionaries, some of which may be None."""
  69. final = {}
  70. for dict in dicts:
  71. if dict is not None:
  72. final.update(dict)
  73. return final
  74. class WADLError(Exception):
  75. """An exception having to do with the state of the WADL application."""
  76. pass
  77. class NoBoundRepresentationError(WADLError):
  78. """An unbound resource was used where wadllib expected a bound resource.
  79. To obtain the value of a resource's parameter, you first must bind
  80. the resource to a representation. Otherwise the resource has no
  81. idea what the value is and doesn't even know if you've given it a
  82. parameter name that makes sense.
  83. """
  84. class UnsupportedMediaTypeError(WADLError):
  85. """A media type was given that's not supported in this context.
  86. A resource can only be bound to media types it has representations
  87. of.
  88. """
  89. class WADLBase(object):
  90. """A base class for objects that contain WADL-derived information."""
  91. class HasParametersMixin:
  92. """A mixin class for objects that have associated Parameter objects."""
  93. def params(self, styles, resource=None):
  94. """Find subsidiary parameters that have the given styles."""
  95. if resource is None:
  96. resource = self.resource
  97. if resource is None:
  98. raise ValueError("Could not find any particular resource")
  99. if self.tag is None:
  100. return []
  101. param_tags = self.tag.findall(wadl_xpath('param'))
  102. if param_tags is None:
  103. return []
  104. return [Parameter(resource, param_tag)
  105. for param_tag in param_tags
  106. if param_tag.attrib.get('style') in styles]
  107. def validate_param_values(self, params, param_values,
  108. enforce_completeness=True, **kw_param_values):
  109. """Make sure the given valueset is valid.
  110. A valueset might be invalid because it contradicts a fixed
  111. value or (if enforce_completeness is True) because it lacks a
  112. required value.
  113. :param params: A list of Parameter objects.
  114. :param param_values: A dictionary of parameter values. May include
  115. paramters whose names are not valid Python identifiers.
  116. :param enforce_completeness: If True, this method will raise
  117. an exception when the given value set lacks a value for a
  118. required parameter.
  119. :param kw_param_values: A dictionary of parameter values.
  120. :return: A dictionary of validated parameter values.
  121. """
  122. param_values = _merge_dicts(param_values, kw_param_values)
  123. validated_values = {}
  124. for param in params:
  125. name = param.name
  126. if param.fixed_value is not None:
  127. if (name in param_values
  128. and param_values[name] != param.fixed_value):
  129. raise ValueError(("Value '%s' for parameter '%s' "
  130. "conflicts with fixed value '%s'")
  131. % (param_values[name], name,
  132. param.fixed_value))
  133. param_values[name] = param.fixed_value
  134. options = [option.value for option in param.options]
  135. if (len(options) > 0 and name in param_values
  136. and param_values[name] not in options):
  137. raise ValueError(("Invalid value '%s' for parameter '%s': "
  138. 'valid values are: "%s"') % (
  139. param_values[name], name, '", "'.join(options)))
  140. if (enforce_completeness and param.is_required
  141. and not name in param_values):
  142. raise ValueError("No value for required parameter '%s'"
  143. % name)
  144. if name in param_values:
  145. validated_values[name] = param_values[name]
  146. del param_values[name]
  147. if len(param_values) > 0:
  148. raise ValueError("Unrecognized parameter(s): '%s'"
  149. % "', '".join(param_values.keys()))
  150. return validated_values
  151. class WADLResolvableDefinition(WADLBase):
  152. """A base class for objects whose definitions may be references."""
  153. def __init__(self, application):
  154. """Initialize with a WADL application.
  155. :param application: A WADLDefinition. Relative links are
  156. assumed to be relative to this object's URL.
  157. """
  158. self._definition = None
  159. self.application = application
  160. def resolve_definition(self):
  161. """Return the definition of this object, wherever it is.
  162. Resource is a good example. A WADL <resource> tag
  163. may contain a large number of nested tags describing a
  164. resource, or it may just contain a 'type' attribute that
  165. references a <resource_type> which contains those same
  166. tags. Resource.resolve_definition() will return the original
  167. Resource object in the first case, and a
  168. ResourceType object in the second case.
  169. """
  170. if self._definition is not None:
  171. return self._definition
  172. object_url = self._get_definition_url()
  173. if object_url is None:
  174. # The object contains its own definition.
  175. # XXX leonardr 2008-05-28:
  176. # This code path is not tested in Launchpad.
  177. self._definition = self
  178. return self
  179. # The object makes reference to some other object. Resolve
  180. # its URL and return it.
  181. xml_id = self.application.lookup_xml_id(object_url)
  182. definition = self._definition_factory(xml_id)
  183. if definition is None:
  184. # XXX leonardr 2008-06-
  185. # This code path is not tested in Launchpad.
  186. # It requires an invalid WADL file that makes
  187. # a reference to a nonexistent tag within the
  188. # same WADL file.
  189. raise KeyError('No such XML ID: "%s"' % object_url)
  190. self._definition = definition
  191. return definition
  192. def _definition_factory(self, id):
  193. """Transform an XML ID into a wadllib wrapper object.
  194. Which kind of object it is depends on the subclass.
  195. """
  196. raise NotImplementedError()
  197. def _get_definition_url(self):
  198. """Find the URL that identifies an external reference.
  199. How to do this depends on the subclass.
  200. """
  201. raise NotImplementedError()
  202. class Resource(WADLResolvableDefinition):
  203. """A resource, possibly bound to a representation."""
  204. def __init__(self, application, url, resource_type,
  205. representation=None, media_type=None,
  206. representation_needs_processing=True,
  207. representation_definition=None):
  208. """
  209. :param application: A WADLApplication.
  210. :param url: The URL to this resource.
  211. :param resource_type: An ElementTree <resource> or <resource_type> tag.
  212. :param representation: A string representation.
  213. :param media_type: The media type of the representation.
  214. :param representation_needs_processing: Set to False if the
  215. 'representation' parameter should be used as
  216. is. Otherwise, it will be transformed from a string into
  217. an appropriate Python data structure, depending on its
  218. media type.
  219. :param representation_definition: A RepresentationDefinition
  220. object describing the structure of this
  221. representation. Used in cases when the representation
  222. isn't the result of sending a standard GET to the
  223. resource.
  224. """
  225. super(Resource, self).__init__(application)
  226. self._url = url
  227. if isinstance(resource_type, _string_types):
  228. # We were passed the URL to a resource type. Look up the
  229. # type object itself
  230. self.tag = self.application.get_resource_type(resource_type).tag
  231. else:
  232. # We were passed an XML tag that describes a resource or
  233. # resource type.
  234. self.tag = resource_type
  235. self.representation = None
  236. if representation is not None:
  237. if media_type == 'application/json':
  238. if representation_needs_processing:
  239. self.representation = json.loads(
  240. _make_unicode(representation))
  241. else:
  242. self.representation = representation
  243. else:
  244. raise UnsupportedMediaTypeError(
  245. "This resource doesn't define a representation for "
  246. "media type %s" % media_type)
  247. self.media_type = media_type
  248. if representation is not None:
  249. if representation_definition is not None:
  250. self.representation_definition = representation_definition
  251. else:
  252. self.representation_definition = (
  253. self.get_representation_definition(self.media_type))
  254. @property
  255. def url(self):
  256. """Return the URL to this resource."""
  257. return self._url
  258. @property
  259. def type_url(self):
  260. """Return the URL to the type definition for this resource, if any."""
  261. if self.tag is None:
  262. return None
  263. url = self.tag.attrib.get('type')
  264. if url is not None:
  265. # This resource is defined in the WADL file.
  266. return url
  267. type_id = self.tag.attrib.get('id')
  268. if type_id is not None:
  269. # This resource was obtained by following a link.
  270. base = URI(self.application.markup_url).ensureSlash()
  271. return str(base) + '#' + type_id
  272. # This resource does not have any associated resource type.
  273. return None
  274. @property
  275. def id(self):
  276. """Return the ID of this resource."""
  277. return self.tag.attrib['id']
  278. def bind(self, representation, media_type='application/json',
  279. representation_needs_processing=True,
  280. representation_definition=None):
  281. """Bind the resource to a representation of that resource.
  282. :param representation: A string representation
  283. :param media_type: The media type of the representation.
  284. :param representation_needs_processing: Set to False if the
  285. 'representation' parameter should be used as
  286. is.
  287. :param representation_definition: A RepresentationDefinition
  288. object describing the structure of this
  289. representation. Used in cases when the representation
  290. isn't the result of sending a standard GET to the
  291. resource.
  292. :return: A Resource bound to a particular representation.
  293. """
  294. return Resource(self.application, self.url, self.tag,
  295. representation, media_type,
  296. representation_needs_processing,
  297. representation_definition)
  298. def get_representation_definition(self, media_type):
  299. """Get a description of one of this resource's representations."""
  300. default_get_response = self.get_method('GET').response
  301. for representation in default_get_response:
  302. representation_tag = representation.resolve_definition().tag
  303. if representation_tag.attrib.get('mediaType') == media_type:
  304. return representation
  305. raise UnsupportedMediaTypeError("No definition for representation "
  306. "with media type %s." % media_type)
  307. def get_method(self, http_method=None, media_type=None, query_params=None,
  308. representation_params=None):
  309. """Look up one of this resource's methods by HTTP method.
  310. :param http_method: The HTTP method used to invoke the desired
  311. method. Case-insensitive and optional.
  312. :param media_type: The media type of the representation
  313. accepted by the method. Optional.
  314. :param query_params: The names and values of any fixed query
  315. parameters used to distinguish between
  316. two methods that use the same HTTP
  317. method. Optional.
  318. :param representation_params: The names and values of any
  319. fixed representation parameters used to
  320. distinguish between two methods that use
  321. the same HTTP method and have the same
  322. media type. Optional.
  323. :return: A MethodDefinition, or None if there's no definition
  324. that fits the given constraints.
  325. """
  326. for method_tag in self._method_tag_iter():
  327. name = method_tag.attrib.get('name', '').lower()
  328. if http_method is None or name == http_method.lower():
  329. method = Method(self, method_tag)
  330. if method.is_described_by(media_type, query_params,
  331. representation_params):
  332. return method
  333. return None
  334. def parameters(self, media_type=None):
  335. """A list of this resource's parameters.
  336. :param media_type: Media type of the representation definition
  337. whose parameters are being named. Must be present unless
  338. this resource is bound to a representation.
  339. :raise NoBoundRepresentationError: If this resource is not
  340. bound to a representation and media_type was not provided.
  341. """
  342. return self._find_representation_definition(
  343. media_type).params(self)
  344. def parameter_names(self, media_type=None):
  345. """A list naming this resource's parameters.
  346. :param media_type: Media type of the representation definition
  347. whose parameters are being named. Must be present unless
  348. this resource is bound to a representation.
  349. :raise NoBoundRepresentationError: If this resource is not
  350. bound to a representation and media_type was not provided.
  351. """
  352. return self._find_representation_definition(
  353. media_type).parameter_names(self)
  354. @property
  355. def method_iter(self):
  356. """An iterator over the methods defined on this resource."""
  357. for method_tag in self._method_tag_iter():
  358. yield Method(self, method_tag)
  359. def get_parameter(self, param_name, media_type=None):
  360. """Find a parameter within a representation definition.
  361. :param param_name: Name of the parameter to find.
  362. :param media_type: Media type of the representation definition
  363. whose parameters are being named. Must be present unless
  364. this resource is bound to a representation.
  365. :raise NoBoundRepresentationError: If this resource is not
  366. bound to a representation and media_type was not provided.
  367. """
  368. definition = self._find_representation_definition(media_type)
  369. representation_tag = definition.tag
  370. for param_tag in representation_tag.findall(wadl_xpath('param')):
  371. if param_tag.attrib.get('name') == param_name:
  372. return Parameter(self, param_tag)
  373. return None
  374. def get_parameter_value(self, parameter):
  375. """Find the value of a parameter, given the Parameter object.
  376. :raise ValueError: If the parameter value can't be converted into
  377. its defined type.
  378. """
  379. if self.representation is None:
  380. raise NoBoundRepresentationError(
  381. "Resource is not bound to any representation.")
  382. if self.media_type == 'application/json':
  383. # XXX leonardr 2008-05-28 A real JSONPath implementation
  384. # should go here. It should execute tag.attrib['path']
  385. # against the JSON representation.
  386. #
  387. # Right now the implementation assumes the JSON
  388. # representation is a hash and treats tag.attrib['name'] as a
  389. # key into the hash.
  390. if parameter.style != 'plain':
  391. raise NotImplementedError(
  392. "Don't know how to find value for a parameter of "
  393. "type %s." % parameter.style)
  394. value = self.representation[parameter.name]
  395. if value is not None:
  396. namespace_url, data_type = self._dereference_namespace(
  397. parameter.tag, parameter.type)
  398. if (namespace_url == XML_SCHEMA_NS_URI
  399. and data_type in ['dateTime', 'date']):
  400. try:
  401. # Parse it as an ISO 8601 date and time.
  402. value = iso_strptime(value)
  403. except ValueError:
  404. # Parse it as an ISO 8601 date.
  405. try:
  406. value = datetime.datetime(
  407. *(time.strptime(value, "%Y-%m-%d")[0:6]))
  408. except ValueError:
  409. # Raise an unadorned ValueError so the client
  410. # can treat the value as a string if they
  411. # want.
  412. raise ValueError(value)
  413. return value
  414. raise NotImplementedError("Path traversal not implemented for "
  415. "a representation of media type %s."
  416. % self.media_type)
  417. def _dereference_namespace(self, tag, value):
  418. """Splits a value into namespace URI and value.
  419. :param tag: A tag to use as context when mapping namespace
  420. names to URIs.
  421. """
  422. if value is not None and ':' in value:
  423. namespace, value = value.split(':', 1)
  424. else:
  425. namespace = ''
  426. ns_map = tag.get(NS_MAP)
  427. namespace_url = ns_map.get(namespace, None)
  428. return namespace_url, value
  429. def _definition_factory(self, id):
  430. """Given an ID, find a ResourceType for that ID."""
  431. return self.application.resource_types.get(id)
  432. def _get_definition_url(self):
  433. """Return the URL that shows where a resource is 'really' defined.
  434. If a resource's capabilities are defined by reference, the
  435. <resource> tag's 'type' attribute will contain the URL to the
  436. <resource_type> that defines them.
  437. """
  438. return self.tag.attrib.get('type')
  439. def _find_representation_definition(self, media_type=None):
  440. """Get the most appropriate representation definition.
  441. If media_type is provided, the most appropriate definition is
  442. the definition of the representation of that media type.
  443. If this resource is bound to a representation, the most
  444. appropriate definition is the definition of that
  445. representation. Otherwise, the most appropriate definition is
  446. the definition of the representation served in response to a
  447. standard GET.
  448. :param media_type: Media type of the definition to find. Must
  449. be present unless the resource is bound to a
  450. representation.
  451. :raise NoBoundRepresentationError: If this resource is not
  452. bound to a representation and media_type was not provided.
  453. :return: A RepresentationDefinition
  454. """
  455. if self.representation is not None:
  456. # We know that when this object was created, a
  457. # representation definition was either looked up, or
  458. # directly passed in along with the representation.
  459. definition = self.representation_definition.resolve_definition()
  460. elif media_type is not None:
  461. definition = self.get_representation_definition(media_type)
  462. else:
  463. raise NoBoundRepresentationError(
  464. "Resource is not bound to any representation, and no media "
  465. "media type was specified.")
  466. return definition.resolve_definition()
  467. def _method_tag_iter(self):
  468. """Iterate over this resource's <method> tags."""
  469. definition = self.resolve_definition().tag
  470. for method_tag in definition.findall(wadl_xpath('method')):
  471. yield method_tag
  472. class Method(WADLBase):
  473. """A wrapper around an XML <method> tag.
  474. """
  475. def __init__(self, resource, method_tag):
  476. """Initialize with a <method> tag.
  477. :param method_tag: An ElementTree <method> tag.
  478. """
  479. self.resource = resource
  480. self.application = self.resource.application
  481. self.tag = method_tag
  482. @property
  483. def request(self):
  484. """Return the definition of a request that invokes the WADL method."""
  485. return RequestDefinition(self, self.tag.find(wadl_xpath('request')))
  486. @property
  487. def response(self):
  488. """Return the definition of the response to the WADL method."""
  489. return ResponseDefinition(self.resource,
  490. self.tag.find(wadl_xpath('response')))
  491. @property
  492. def id(self):
  493. """The XML ID of the WADL method definition."""
  494. return self.tag.attrib.get('id')
  495. @property
  496. def name(self):
  497. """The name of the WADL method definition.
  498. This is also the name of the HTTP method (GET, POST, etc.)
  499. that should be used to invoke the WADL method.
  500. """
  501. return self.tag.attrib.get('name').lower()
  502. def build_request_url(self, param_values=None, **kw_param_values):
  503. """Return the request URL to use to invoke this method."""
  504. return self.request.build_url(param_values, **kw_param_values)
  505. def build_representation(self, media_type=None,
  506. param_values=None, **kw_param_values):
  507. """Build a representation to be sent when invoking this method.
  508. :return: A 2-tuple of (media_type, representation).
  509. """
  510. return self.request.representation(
  511. media_type, param_values, **kw_param_values)
  512. def is_described_by(self, media_type=None, query_values=None,
  513. representation_values=None):
  514. """Returns true if this method fits the given constraints.
  515. :param media_type: The method must accept this media type as a
  516. representation.
  517. :param query_values: These key-value pairs must be acceptable
  518. as values for this method's query
  519. parameters. This need not be a complete set
  520. of parameters acceptable to the method.
  521. :param representation_values: These key-value pairs must be
  522. acceptable as values for this method's
  523. representation parameters. Again, this need
  524. not be a complete set of parameters
  525. acceptable to the method.
  526. """
  527. representation = None
  528. if media_type is not None:
  529. representation = self.request.get_representation_definition(
  530. media_type)
  531. if representation is None:
  532. return False
  533. if query_values is not None and len(query_values) > 0:
  534. request = self.request
  535. if request is None:
  536. # This method takes no special request
  537. # parameters, so it can't match.
  538. return False
  539. try:
  540. request.validate_param_values(
  541. request.query_params, query_values, False)
  542. except ValueError:
  543. return False
  544. # At this point we know the media type and query values match.
  545. if (representation_values is None
  546. or len(representation_values) == 0):
  547. return True
  548. if representation is not None:
  549. return representation.is_described_by(
  550. representation_values)
  551. for representation in self.request.representations:
  552. try:
  553. representation.validate_param_values(
  554. representation.params(self.resource),
  555. representation_values, False)
  556. return True
  557. except ValueError:
  558. pass
  559. return False
  560. class RequestDefinition(WADLBase, HasParametersMixin):
  561. """A wrapper around the description of the request invoking a method."""
  562. def __init__(self, method, request_tag):
  563. """Initialize with a <request> tag.
  564. :param resource: The resource to which this request can be sent.
  565. :param request_tag: An ElementTree <request> tag.
  566. """
  567. self.method = method
  568. self.resource = self.method.resource
  569. self.application = self.resource.application
  570. self.tag = request_tag
  571. @property
  572. def query_params(self):
  573. """Return the query parameters for this method."""
  574. return self.params(['query'])
  575. @property
  576. def representations(self):
  577. for definition in self.tag.findall(wadl_xpath('representation')):
  578. yield RepresentationDefinition(
  579. self.application, self.resource, definition)
  580. def get_representation_definition(self, media_type=None):
  581. """Return the appropriate representation definition."""
  582. for representation in self.representations:
  583. if media_type is None or representation.media_type == media_type:
  584. return representation
  585. return None
  586. def representation(self, media_type=None, param_values=None,
  587. **kw_param_values):
  588. """Build a representation to be sent along with this request.
  589. :return: A 2-tuple of (media_type, representation).
  590. """
  591. definition = self.get_representation_definition(media_type)
  592. if definition is None:
  593. raise TypeError("Cannot build representation of media type %s"
  594. % media_type)
  595. return definition.bind(param_values, **kw_param_values)
  596. def build_url(self, param_values=None, **kw_param_values):
  597. """Return the request URL to use to invoke this method."""
  598. validated_values = self.validate_param_values(
  599. self.query_params, param_values, **kw_param_values)
  600. url = self.resource.url
  601. if len(validated_values) > 0:
  602. if '?' in url:
  603. append = '&'
  604. else:
  605. append = '?'
  606. url += append + urlencode(sorted(validated_values.items()))
  607. return url
  608. class ResponseDefinition(HasParametersMixin):
  609. """A wrapper around the description of a response to a method."""
  610. # XXX leonardr 2008-05-29 it would be nice to have
  611. # ResponseDefinitions for POST operations and nonstandard GET
  612. # operations say what representations and/or status codes you get
  613. # back. Getting this to work with Launchpad requires work on the
  614. # Launchpad side.
  615. def __init__(self, resource, response_tag, headers=None):
  616. """Initialize with a <response> tag.
  617. :param response_tag: An ElementTree <response> tag.
  618. """
  619. self.application = resource.application
  620. self.resource = resource
  621. self.tag = response_tag
  622. self.headers = headers
  623. def __iter__(self):
  624. """Get an iterator over the representation definitions.
  625. These are the representations returned in response to an
  626. invocation of this method.
  627. """
  628. path = wadl_xpath('representation')
  629. for representation_tag in self.tag.findall(path):
  630. yield RepresentationDefinition(
  631. self.resource.application, self.resource, representation_tag)
  632. def bind(self, headers):
  633. """Bind the response to a set of HTTP headers.
  634. A WADL response can have associated header parameters, but no
  635. other kind.
  636. """
  637. return ResponseDefinition(self.resource, self.tag, headers)
  638. def get_parameter(self, param_name):
  639. """Find a header parameter within the response."""
  640. for param_tag in self.tag.findall(wadl_xpath('param')):
  641. if (param_tag.attrib.get('name') == param_name
  642. and param_tag.attrib.get('style') == 'header'):
  643. return Parameter(self, param_tag)
  644. return None
  645. def get_parameter_value(self, parameter):
  646. """Find the value of a parameter, given the Parameter object."""
  647. if self.headers is None:
  648. raise NoBoundRepresentationError(
  649. "Response object is not bound to any headers.")
  650. if parameter.style != 'header':
  651. raise NotImplementedError(
  652. "Don't know how to find value for a parameter of "
  653. "type %s." % parameter.style)
  654. return self.headers.get(parameter.name)
  655. def get_representation_definition(self, media_type):
  656. """Get one of the possible representations of the response."""
  657. if self.tag is None:
  658. return None
  659. for representation in self:
  660. if representation.media_type == media_type:
  661. return representation
  662. return None
  663. class RepresentationDefinition(WADLResolvableDefinition, HasParametersMixin):
  664. """A definition of the structure of a representation."""
  665. def __init__(self, application, resource, representation_tag):
  666. super(RepresentationDefinition, self).__init__(application)
  667. self.resource = resource
  668. self.tag = representation_tag
  669. def params(self, resource):
  670. return super(RepresentationDefinition, self).params(
  671. ['query', 'plain'], resource)
  672. def parameter_names(self, resource):
  673. """Return the names of all parameters."""
  674. return [param.name for param in self.params(resource)]
  675. @property
  676. def media_type(self):
  677. """The media type of the representation described here."""
  678. return self.resolve_definition().tag.attrib['mediaType']
  679. def _make_boundary(self, all_parts):
  680. """Make a random boundary that does not appear in `all_parts`."""
  681. _width = len(repr(sys.maxsize - 1))
  682. _fmt = '%%0%dd' % _width
  683. token = random.randrange(sys.maxsize)
  684. boundary = ('=' * 15) + (_fmt % token) + '=='
  685. if all_parts is None:
  686. return boundary
  687. b = boundary
  688. counter = 0
  689. while True:
  690. pattern = ('^--' + re.escape(b) + '(--)?$').encode('ascii')
  691. if not re.search(pattern, all_parts, flags=re.MULTILINE):
  692. break
  693. b = boundary + '.' + str(counter)
  694. counter += 1
  695. return b
  696. def _write_headers(self, buf, headers):
  697. """Write MIME headers to a file object."""
  698. for key, value in headers:
  699. buf.write(key.encode('UTF-8'))
  700. buf.write(b': ')
  701. buf.write(value.encode('UTF-8'))
  702. buf.write(b'\r\n')
  703. buf.write(b'\r\n')
  704. def _write_boundary(self, buf, boundary, closing=False):
  705. """Write a multipart boundary to a file object."""
  706. buf.write(b'--')
  707. buf.write(boundary.encode('UTF-8'))
  708. if closing:
  709. buf.write(b'--')
  710. buf.write(b'\r\n')
  711. def _generate_multipart_form(self, parts):
  712. """Generate a multipart/form-data message.
  713. This is very loosely based on the email module in the Python standard
  714. library. However, that module doesn't really support directly embedding
  715. binary data in a form: various versions of Python have mangled line
  716. separators in different ways, and none of them get it quite right.
  717. Since we only need a tiny subset of MIME here, it's easier to implement
  718. it ourselves.
  719. :return: a tuple of two elements: the Content-Type of the message, and
  720. the entire encoded message as a byte string.
  721. """
  722. # Generate the subparts first so that we can calculate a safe boundary.
  723. encoded_parts = []
  724. for is_binary, name, value in parts:
  725. buf = io.BytesIO()
  726. if is_binary:
  727. ctype = 'application/octet-stream'
  728. # RFC 7578 says that the filename parameter isn't mandatory
  729. # in our case, but without it cgi.FieldStorage tries to
  730. # decode as text on Python 3.
  731. cdisp = 'form-data; name="%s"; filename="%s"' % (
  732. quote(name), quote(name))
  733. else:
  734. ctype = 'text/plain; charset="utf-8"'
  735. cdisp = 'form-data; name="%s"' % quote(name)
  736. self._write_headers(buf, [
  737. ('MIME-Version', '1.0'),
  738. ('Content-Type', ctype),
  739. ('Content-Disposition', cdisp),
  740. ])
  741. if is_binary:
  742. if not isinstance(value, bytes):
  743. raise TypeError('bytes payload expected: %s' % type(value))
  744. buf.write(value)
  745. else:
  746. if not isinstance(value, _string_types):
  747. raise TypeError(
  748. 'string payload expected: %s' % type(value))
  749. lines = re.split(r'\r\n|\r|\n', value)
  750. for line in lines[:-1]:
  751. buf.write(line.encode('UTF-8'))
  752. buf.write(b'\r\n')
  753. buf.write(lines[-1].encode('UTF-8'))
  754. encoded_parts.append(buf.getvalue())
  755. # Create a suitable boundary.
  756. boundary = self._make_boundary(b'\r\n'.join(encoded_parts))
  757. # Now we can write the multipart headers, followed by all the parts.
  758. buf = io.BytesIO()
  759. ctype = 'multipart/form-data; boundary="%s"' % quote(boundary)
  760. self._write_headers(buf, [
  761. ('MIME-Version', '1.0'),
  762. ('Content-Type', ctype),
  763. ])
  764. for encoded_part in encoded_parts:
  765. self._write_boundary(buf, boundary)
  766. buf.write(encoded_part)
  767. buf.write(b'\r\n')
  768. self._write_boundary(buf, boundary, closing=True)
  769. return ctype, buf.getvalue()
  770. def bind(self, param_values, **kw_param_values):
  771. """Bind the definition to parameter values, creating a document.
  772. :return: A 2-tuple (media_type, document).
  773. """
  774. definition = self.resolve_definition()
  775. params = definition.params(self.resource)
  776. validated_values = self.validate_param_values(
  777. params, param_values, **kw_param_values)
  778. media_type = self.media_type
  779. if media_type == 'application/x-www-form-urlencoded':
  780. doc = urlencode(sorted(validated_values.items()))
  781. elif media_type == 'multipart/form-data':
  782. parts = []
  783. missing = object()
  784. for param in params:
  785. value = validated_values.get(param.name, missing)
  786. if value is not missing:
  787. parts.append((param.type == 'binary', param.name, value))
  788. media_type, doc = self._generate_multipart_form(parts)
  789. elif media_type == 'application/json':
  790. doc = json.dumps(validated_values)
  791. else:
  792. raise ValueError("Unsupported media type: '%s'" % media_type)
  793. return media_type, doc
  794. def _definition_factory(self, id):
  795. """Turn a representation ID into a RepresentationDefinition."""
  796. return self.application.representation_definitions.get(id)
  797. def _get_definition_url(self):
  798. """Find the URL containing the representation's 'real' definition.
  799. If a representation's structure is defined by reference, the
  800. <representation> tag's 'href' attribute will contain the URL
  801. to the <representation> that defines the structure.
  802. """
  803. return self.tag.attrib.get('href')
  804. class Parameter(WADLBase):
  805. """One of the parameters of a representation definition."""
  806. def __init__(self, value_container, tag):
  807. """Initialize with respect to a value container.
  808. :param value_container: Usually the resource whose representation
  809. has this parameter. If the resource is bound to a representation,
  810. you'll be able to find the value of this parameter in the
  811. representation. This may also be a server response whose headers
  812. define a value for this parameter.
  813. :tag: The ElementTree <param> tag for this parameter.
  814. """
  815. self.application = value_container.application
  816. self.value_container = value_container
  817. self.tag = tag
  818. @property
  819. def name(self):
  820. """The name of this parameter."""
  821. return self.tag.attrib.get('name')
  822. @property
  823. def style(self):
  824. """The style of this parameter."""
  825. return self.tag.attrib.get('style')
  826. @property
  827. def type(self):
  828. """The XSD type of this parameter."""
  829. return self.tag.attrib.get('type')
  830. @property
  831. def fixed_value(self):
  832. """The value to which this parameter is fixed, if any.
  833. A fixed parameter must be present in invocations of a WADL
  834. method, and it must have a particular value. This is commonly
  835. used to designate one parameter as containing the name of the
  836. server-side operation to be invoked.
  837. """
  838. return self.tag.attrib.get('fixed')
  839. @property
  840. def is_required(self):
  841. """Whether or not a value for this parameter is required."""
  842. return (self.tag.attrib.get('required', 'false').lower()
  843. in ['1', 'true'])
  844. def get_value(self):
  845. """The value of this parameter in the bound representation/headers.
  846. :raise NoBoundRepresentationError: If this parameter's value
  847. container is not bound to a representation or a set of
  848. headers.
  849. """
  850. return self.value_container.get_parameter_value(self)
  851. @property
  852. def options(self):
  853. """Return the set of acceptable values for this parameter."""
  854. return [Option(self, option_tag)
  855. for option_tag in self.tag.findall(wadl_xpath('option'))]
  856. @property
  857. def link(self):
  858. """Get the link to another resource.
  859. The link may be examined and, if its type is of a known WADL
  860. description, it may be followed.
  861. :return: A Link object, or None.
  862. """
  863. link_tag = self.tag.find(wadl_xpath('link'))
  864. if link_tag is None:
  865. return None
  866. return Link(self, link_tag)
  867. @property
  868. def linked_resource(self):
  869. """Follow a link from this parameter to a new resource.
  870. This only works for parameters whose WADL definition includes a
  871. <link> tag that points to a known WADL description.
  872. :return: A Resource object for the resource at the other end
  873. of the link.
  874. """
  875. link = self.link
  876. if link is None:
  877. raise ValueError("This parameter isn't a link to anything.")
  878. return link.follow
  879. class Option(WADLBase):
  880. """One of a set of possible values for a parameter."""
  881. def __init__(self, parameter, option_tag):
  882. """Initialize the option.
  883. :param parameter: A Parameter.
  884. :param link_tag: An ElementTree <option> tag.
  885. """
  886. self.parameter = parameter
  887. self.tag = option_tag
  888. @property
  889. def value(self):
  890. return self.tag.attrib.get('value')
  891. class Link(WADLResolvableDefinition):
  892. """A link from one resource to another.
  893. Calling resolve_definition() on a Link will give you a Resource for the
  894. type of resource linked to. An alias for this is 'follow'.
  895. """
  896. def __init__(self, parameter, link_tag):
  897. """Initialize the link.
  898. :param parameter: A Parameter.
  899. :param link_tag: An ElementTree <link> tag.
  900. """
  901. super(Link, self).__init__(parameter.application)
  902. self.parameter = parameter
  903. self.tag = link_tag
  904. @property
  905. def follow(self):
  906. """Follow the link to another Resource."""
  907. if not self.can_follow:
  908. raise WADLError("Cannot follow a link when the target has no "
  909. "WADL description. Try using a general HTTP "
  910. "client instead.")
  911. return self.resolve_definition()
  912. @property
  913. def can_follow(self):
  914. """Can this link be followed within wadllib?
  915. wadllib can follow a link if it points to a resource that has
  916. a WADL definition.
  917. """
  918. try:
  919. definition_url = self._get_definition_url()
  920. except WADLError:
  921. return False
  922. return True
  923. def _definition_factory(self, id):
  924. """Turn a resource type ID into a ResourceType."""
  925. return Resource(
  926. self.application, self.parameter.get_value(),
  927. self.application.resource_types.get(id).tag)
  928. def _get_definition_url(self):
  929. """Find the URL containing the definition ."""
  930. type = self.tag.attrib.get('resource_type')
  931. if type is None:
  932. raise WADLError("Parameter is a link, but not to a resource "
  933. "with a known WADL description.")
  934. return type
  935. class ResourceType(WADLBase):
  936. """A wrapper around an XML <resource_type> tag."""
  937. def __init__(self, resource_type_tag):
  938. """Initialize with a <resource_type> tag.
  939. :param resource_type_tag: An ElementTree <resource_type> tag.
  940. """
  941. self.tag = resource_type_tag
  942. class Application(WADLBase):
  943. """A WADL document made programmatically accessible."""
  944. def __init__(self, markup_url, markup):
  945. """Parse WADL and find the most important parts of the document.
  946. :param markup_url: The URL from which this document was obtained.
  947. :param markup: The WADL markup itself, or an open filehandle to it.
  948. """
  949. self.markup_url = markup_url
  950. if hasattr(markup, 'read'):
  951. self.doc = self._from_stream(markup)
  952. else:
  953. self.doc = self._from_string(markup)
  954. self.resources = self.doc.find(wadl_xpath('resources'))
  955. self.resource_base = self.resources.attrib.get('base')
  956. self.representation_definitions = {}
  957. self.resource_types = {}
  958. for representation in self.doc.findall(wadl_xpath('representation')):
  959. id = representation.attrib.get('id')
  960. if id is not None:
  961. definition = RepresentationDefinition(
  962. self, None, representation)
  963. self.representation_definitions[id] = definition
  964. for resource_type in self.doc.findall(wadl_xpath('resource_type')):
  965. id = resource_type.attrib['id']
  966. self.resource_types[id] = ResourceType(resource_type)
  967. def _from_stream(self, stream):
  968. """Turns markup into a document.
  969. Just a wrapper around ElementTree which keeps track of namespaces.
  970. """
  971. events = "start", "start-ns", "end-ns"
  972. root = None
  973. ns_map = []
  974. for event, elem in ET.iterparse(stream, events):
  975. if event == "start-ns":
  976. ns_map.append(elem)
  977. elif event == "end-ns":
  978. ns_map.pop()
  979. elif event == "start":
  980. if root is None:
  981. root = elem
  982. elem.set(NS_MAP, dict(ns_map))
  983. return ET.ElementTree(root)
  984. def _from_string(self, markup):
  985. """Turns markup into a document."""
  986. if not isinstance(markup, bytes):
  987. markup = markup.encode("UTF-8")
  988. return self._from_stream(io.BytesIO(markup))
  989. def get_resource_type(self, resource_type_url):
  990. """Retrieve a resource type by the URL of its description."""
  991. xml_id = self.lookup_xml_id(resource_type_url)
  992. resource_type = self.resource_types.get(xml_id)
  993. if resource_type is None:
  994. raise KeyError('No such XML ID: "%s"' % resource_type_url)
  995. return resource_type
  996. def lookup_xml_id(self, url):
  997. """A helper method for locating a part of a WADL document.
  998. :param url: The URL (with anchor) of the desired part of the
  999. WADL document.
  1000. :return: The XML ID corresponding to the anchor.
  1001. """
  1002. markup_uri = URI(self.markup_url).ensureNoSlash()
  1003. markup_uri.fragment = None
  1004. if url.startswith('http'):
  1005. # It's an absolute URI.
  1006. this_uri = URI(url).ensureNoSlash()
  1007. else:
  1008. # It's a relative URI.
  1009. this_uri = markup_uri.resolve(url)
  1010. possible_xml_id = this_uri.fragment
  1011. this_uri.fragment = None
  1012. if this_uri == markup_uri:
  1013. # The URL pointed elsewhere within the same WADL document.
  1014. # Return its fragment.
  1015. return possible_xml_id
  1016. # XXX leonardr 2008-05-28:
  1017. # This needs to be implemented eventually for Launchpad so
  1018. # that a script using this client can navigate from a WADL
  1019. # representation of a non-root resource to its definition at
  1020. # the server root.
  1021. raise NotImplementedError("Can't look up definition in another "
  1022. "url (%s)" % url)
  1023. def get_resource_by_path(self, path):
  1024. """Locate one of the resources described by this document.
  1025. :param path: The path to the resource.
  1026. """
  1027. # XXX leonardr 2008-05-27 This method only finds top-level
  1028. # resources. That's all we need for Launchpad because we don't
  1029. # define nested resources yet.
  1030. matching = [resource for resource in self.resources
  1031. if resource.attrib['path'] == path]
  1032. if len(matching) < 1:
  1033. return None
  1034. if len(matching) > 1:
  1035. raise WADLError("More than one resource defined with path %s"
  1036. % path)
  1037. return Resource(
  1038. self, merge(self.resource_base, path, True), matching[0])