resource.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195
  1. # Copyright 2008 Canonical Ltd.
  2. # This file is part of lazr.restfulclient.
  3. #
  4. # lazr.restfulclient is free software: you can redistribute it and/or
  5. # modify it under the terms of the GNU Lesser General Public License
  6. # as published by the Free Software Foundation, either version 3 of
  7. # the License, or (at your option) any later version.
  8. #
  9. # lazr.restfulclient is distributed in the hope that it will be
  10. # useful, but WITHOUT ANY WARRANTY; without even the implied warranty
  11. # of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. # Lesser General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Lesser General Public
  15. # License along with lazr.restfulclient. If not, see
  16. # <http://www.gnu.org/licenses/>.
  17. """Common support for web service resources."""
  18. __metaclass__ = type
  19. __all__ = [
  20. "Collection",
  21. "CollectionWithKeyBasedLookup",
  22. "Entry",
  23. "NamedOperation",
  24. "Resource",
  25. "ServiceRoot",
  26. ]
  27. from email.message import Message
  28. from io import BytesIO
  29. from json import dumps, loads
  30. try:
  31. # Python 3.
  32. from urllib.parse import parse_qs, unquote, urlencode, urljoin, urlparse
  33. except ImportError:
  34. from urlparse import urljoin, urlparse, parse_qs
  35. from urllib import unquote, urlencode
  36. import sys
  37. if sys.version_info[0] >= 3:
  38. text_type = str
  39. binary_type = bytes
  40. else:
  41. text_type = unicode # noqa: F821
  42. binary_type = str
  43. from wadllib.application import Resource as WadlResource
  44. from lazr.restfulclient import __version__
  45. from lazr.restfulclient._browser import Browser, RestfulHttp
  46. from lazr.restfulclient._json import DatetimeJSONEncoder
  47. from lazr.restfulclient.errors import HTTPError
  48. from lazr.uri import URI
  49. missing = object()
  50. class HeaderDictionary:
  51. """A dictionary that bridges httplib2's and wadllib's expectations.
  52. httplib2 expects all header dictionary access to give lowercase
  53. header names. wadllib expects to access the header exactly as it's
  54. specified in the WADL file, which means the official HTTP header name.
  55. This class transforms keys to lowercase before doing a lookup on
  56. the underlying dictionary. That way wadllib can pass in the
  57. official header name and httplib2 will get the lowercased name.
  58. """
  59. def __init__(self, wrapped_dictionary):
  60. self.wrapped_dictionary = wrapped_dictionary
  61. def get(self, key, default=None):
  62. """Retrieve a value, converting the key to lowercase."""
  63. return self.wrapped_dictionary.get(key.lower())
  64. def __getitem__(self, key):
  65. """Retrieve a value, converting the key to lowercase."""
  66. value = self.get(key, missing)
  67. if value is missing:
  68. raise KeyError(key)
  69. return value
  70. class RestfulBase:
  71. """Base class for classes that know about lazr.restful services."""
  72. JSON_MEDIA_TYPE = "application/json"
  73. def _transform_resources_to_links(self, dictionary):
  74. new_dictionary = {}
  75. for key, value in dictionary.items():
  76. if isinstance(value, Resource):
  77. value = value.self_link
  78. new_dictionary[self._get_external_param_name(key)] = value
  79. return new_dictionary
  80. def _get_external_param_name(self, param_name):
  81. """Turn a lazr.restful name into something to be sent over HTTP.
  82. For resources this may involve sticking '_link' or
  83. '_collection_link' on the end of the parameter name. For
  84. arguments to named operations, the parameter name is returned
  85. as is.
  86. """
  87. return param_name
  88. class Resource(RestfulBase):
  89. """Base class for lazr.restful HTTP resources."""
  90. def __init__(self, root, wadl_resource):
  91. """Initialize with respect to a wadllib Resource object."""
  92. if root is None:
  93. # This _is_ the root.
  94. root = self
  95. # These values need to be put directly into __dict__ to avoid
  96. # calling __setattr__, which would cause an infinite recursion.
  97. self.__dict__["_root"] = root
  98. self.__dict__["_wadl_resource"] = wadl_resource
  99. FIND_COLLECTIONS = object()
  100. FIND_ENTRIES = object()
  101. FIND_ATTRIBUTES = object()
  102. @property
  103. def lp_collections(self):
  104. """Name the collections this resource links to."""
  105. return self._get_parameter_names(self.FIND_COLLECTIONS)
  106. @property
  107. def lp_entries(self):
  108. """Name the entries this resource links to."""
  109. return self._get_parameter_names(self.FIND_ENTRIES)
  110. @property
  111. def lp_attributes(self):
  112. """Name this resource's scalar attributes."""
  113. return self._get_parameter_names(self.FIND_ATTRIBUTES)
  114. @property
  115. def lp_operations(self):
  116. """Name all of this resource's custom operations."""
  117. # This library distinguishes between named operations by the
  118. # value they give for ws.op, not by their WADL names or IDs.
  119. names = []
  120. for method in self._wadl_resource.method_iter:
  121. name = method.name.lower()
  122. if name == "get":
  123. params = method.request.params(["query", "plain"])
  124. elif name == "post":
  125. for media_type in [
  126. "application/x-www-form-urlencoded",
  127. "multipart/form-data",
  128. ]:
  129. definition = method.request.get_representation_definition(
  130. media_type
  131. )
  132. if definition is not None:
  133. definition = definition.resolve_definition()
  134. break
  135. params = definition.params(self._wadl_resource)
  136. for param in params:
  137. if param.name == "ws.op":
  138. names.append(param.fixed_value)
  139. break
  140. return names
  141. @property
  142. def __members__(self):
  143. """A hook into dir() that returns web service-derived members."""
  144. return self._get_parameter_names(
  145. self.FIND_COLLECTIONS, self.FIND_ENTRIES, self.FIND_ATTRIBUTES
  146. )
  147. __methods__ = lp_operations
  148. def _get_parameter_names(self, *kinds):
  149. """Retrieve some subset of the resource's parameters."""
  150. names = []
  151. for parameter in self._wadl_resource.parameters(self.JSON_MEDIA_TYPE):
  152. name = parameter.name
  153. link = parameter.link
  154. if name != "self_link" and link is not None and link.can_follow:
  155. # This is a link to a resource with a WADL
  156. # description. Since this is a lazr.restful web
  157. # service, we know it's either an entry or a
  158. # collection, and that its name ends with '_link' or
  159. # '_collection_link', respectively.
  160. #
  161. # self_link is a special case. 'obj.self' will always
  162. # work, but it's not useful. 'obj.self_link' is
  163. # useful, so we advertise the scalar value instead.
  164. if name.endswith("_collection_link"):
  165. # It's a link to a collection.
  166. if self.FIND_COLLECTIONS in kinds:
  167. names.append(name[:-16])
  168. else:
  169. # It's a link to an entry.
  170. if self.FIND_ENTRIES in kinds:
  171. names.append(name[:-5])
  172. else:
  173. # There are three possibilities. This is not a link at
  174. # all, it's a link to a resource not described by
  175. # WADL, or it's the 'self_link'. Either way,
  176. # lazr.restfulclient should treat this parameter as a
  177. # scalar attribute.
  178. if self.FIND_ATTRIBUTES in kinds:
  179. names.append(name)
  180. return names
  181. def lp_has_parameter(self, param_name):
  182. """Does this resource have a parameter with the given name?"""
  183. return self._get_external_param_name(param_name) is not None
  184. def lp_get_parameter(self, param_name):
  185. """Get the value of one of the resource's parameters.
  186. :return: A scalar value if the parameter is not a link. A new
  187. Resource object, whose resource is bound to a
  188. representation, if the parameter is a link.
  189. """
  190. self._ensure_representation()
  191. for suffix in ["_link", "_collection_link"]:
  192. param = self._wadl_resource.get_parameter(param_name + suffix)
  193. if param is not None:
  194. try:
  195. param.get_value()
  196. except KeyError:
  197. # The parameter could have been present, but isn't.
  198. # Try the next parameter.
  199. continue
  200. if param.get_value() is None:
  201. # This parameter is a link to another object, but
  202. # there's no other object. Return None rather than
  203. # chasing down the nonexistent other object.
  204. return None
  205. linked_resource = param.linked_resource
  206. return self._create_bound_resource(
  207. self._root, linked_resource, param_name=param.name
  208. )
  209. param = self._wadl_resource.get_parameter(param_name)
  210. if param is None:
  211. raise KeyError("No such parameter: %s" % param_name)
  212. return param.get_value()
  213. def lp_get_named_operation(self, operation_name):
  214. """Get a custom operation with the given name.
  215. :return: A NamedOperation instance that can be called with
  216. appropriate arguments to invoke the operation.
  217. """
  218. params = {"ws.op": operation_name}
  219. method = self._wadl_resource.get_method("get", query_params=params)
  220. if method is None:
  221. method = self._wadl_resource.get_method(
  222. "post", representation_params=params
  223. )
  224. if method is None:
  225. raise KeyError("No operation with name: %s" % operation_name)
  226. return NamedOperation(self._root, self, method)
  227. @classmethod
  228. def _create_bound_resource(
  229. cls,
  230. root,
  231. resource,
  232. representation=None,
  233. representation_media_type="application/json",
  234. representation_needs_processing=True,
  235. representation_definition=None,
  236. param_name=None,
  237. ):
  238. """Create a lazr.restful Resource subclass from a wadllib Resource.
  239. :param resource: The wadllib Resource to wrap.
  240. :param representation: A previously fetched representation of
  241. this resource, to be reused. If not provided, this method
  242. will act just like the Resource constructor.
  243. :param representation_media_type: The media type of any previously
  244. fetched representation.
  245. :param representation_needs_processing: Set to False if the
  246. 'representation' parameter should be used as
  247. is.
  248. :param representation_definition: A wadllib
  249. RepresentationDefinition object describing the structure
  250. of this representation. Used in cases when the representation
  251. isn't the result of sending a standard GET to the resource.
  252. :param param_name: The name of the link that was followed to get
  253. to this resource.
  254. :return: An instance of the appropriate lazr.restful Resource
  255. subclass.
  256. """
  257. # We happen to know that all lazr.restful resource types are
  258. # defined in a single document. Turn the resource's type_url
  259. # into an anchor into that document: this is its resource
  260. # type. Then look up a client-side class that corresponds to
  261. # the resource type.
  262. type_url = resource.type_url
  263. resource_type = urlparse(type_url)[-1]
  264. default = Entry
  265. if type_url.endswith("-page") or (
  266. param_name is not None and param_name.endswith("_collection_link")
  267. ):
  268. default = Collection
  269. r_class = root.RESOURCE_TYPE_CLASSES.get(resource_type, default)
  270. if representation is not None:
  271. # We've been given a representation. Bind the resource
  272. # immediately.
  273. resource = resource.bind(
  274. representation,
  275. representation_media_type,
  276. representation_needs_processing,
  277. representation_definition=representation_definition,
  278. )
  279. else:
  280. # We'll fetch a representation and bind the resource when
  281. # necessary.
  282. pass
  283. return r_class(root, resource)
  284. def lp_refresh(self, new_url=None, etag=None):
  285. """Update this resource's representation."""
  286. if new_url is not None:
  287. self._wadl_resource._url = new_url
  288. headers = {}
  289. if etag is not None:
  290. headers["If-None-Match"] = etag
  291. representation = self._root._browser.get(
  292. self._wadl_resource, headers=headers
  293. )
  294. if representation == self._root._browser.NOT_MODIFIED:
  295. # The entry wasn't modified. No need to do anything.
  296. return
  297. # __setattr__ assumes we're setting an attribute of the resource,
  298. # so we manipulate __dict__ directly.
  299. self.__dict__["_wadl_resource"] = self._wadl_resource.bind(
  300. representation, self.JSON_MEDIA_TYPE
  301. )
  302. def __getattr__(self, attr):
  303. """Try to retrive a named operation or parameter of the given name."""
  304. try:
  305. return self.lp_get_named_operation(attr)
  306. except KeyError:
  307. pass
  308. try:
  309. return self.lp_get_parameter(attr)
  310. except KeyError:
  311. raise AttributeError(
  312. "%s object has no attribute '%s'" % (self, attr)
  313. )
  314. def lp_values_for(self, param_name):
  315. """Find the set of possible values for a parameter."""
  316. parameter = self._wadl_resource.get_parameter(
  317. param_name, self.JSON_MEDIA_TYPE
  318. )
  319. options = parameter.options
  320. if len(options) > 0:
  321. return [option.value for option in options]
  322. return None
  323. def _get_external_param_name(self, param_name):
  324. """What's this parameter's name in the underlying representation?"""
  325. for suffix in ["_link", "_collection_link", ""]:
  326. name = param_name + suffix
  327. if self._wadl_resource.get_parameter(name):
  328. return name
  329. return None
  330. def _ensure_representation(self):
  331. """Make sure this resource has a representation fetched."""
  332. if self._wadl_resource.representation is None:
  333. # Get a representation of the linked resource.
  334. representation = self._root._browser.get(self._wadl_resource)
  335. if isinstance(representation, binary_type):
  336. representation = representation.decode("utf-8")
  337. representation = loads(representation)
  338. # In rare cases, the resource type served by the
  339. # server conflicts with the type the client thought
  340. # this resource had. When this happens, the server
  341. # value takes precedence.
  342. #
  343. # XXX This should probably be moved into a hook method
  344. # defined by Entry, since it's not relevant to other
  345. # resource types.
  346. if isinstance(representation, dict):
  347. type_link = representation["resource_type_link"]
  348. if (
  349. type_link is not None
  350. and type_link != self._wadl_resource.type_url
  351. ):
  352. resource_type = self._root._wadl.get_resource_type(
  353. type_link
  354. )
  355. self._wadl_resource.tag = resource_type.tag
  356. self.__dict__["_wadl_resource"] = self._wadl_resource.bind(
  357. representation,
  358. self.JSON_MEDIA_TYPE,
  359. representation_needs_processing=False,
  360. )
  361. def __ne__(self, other):
  362. """Inequality operator."""
  363. return not self == other
  364. class ScalarValue(Resource):
  365. """A resource representing a single scalar value."""
  366. @property
  367. def value(self):
  368. """Return the scalar value."""
  369. self._ensure_representation()
  370. return self._wadl_resource.representation
  371. class HostedFile(Resource):
  372. """A resource representing a file managed by a lazr.restful service."""
  373. def open(self, mode="r", content_type=None, filename=None):
  374. """Open the file on the server for read or write access."""
  375. if mode in ("r", "w"):
  376. return HostedFileBuffer(self, mode, content_type, filename)
  377. else:
  378. raise ValueError("Invalid mode. Supported modes are: r, w")
  379. def delete(self):
  380. """Delete the file from the server."""
  381. self._root._browser.delete(self._wadl_resource.url)
  382. def _get_parameter_names(self, *kinds):
  383. """HostedFile objects define no web service parameters."""
  384. return []
  385. def __eq__(self, other):
  386. """Equality comparison.
  387. Two hosted files are the same if they have the same URL.
  388. There is no need to check the contents because the only way to
  389. retrieve or modify the hosted file contents is to open a
  390. filehandle, which goes direct to the server.
  391. """
  392. return (
  393. other is not None
  394. and self._wadl_resource.url == other._wadl_resource.url
  395. )
  396. class ServiceRoot(Resource):
  397. """Entry point to the service. Subclass this for a service-specific client.
  398. :ivar credentials: The credentials instance used to access Launchpad.
  399. """
  400. # Custom subclasses of Resource to use when
  401. # instantiating resources of a certain WADL type.
  402. RESOURCE_TYPE_CLASSES = {
  403. "HostedFile": HostedFile,
  404. "ScalarValue": ScalarValue,
  405. }
  406. def __init__(
  407. self,
  408. authorizer,
  409. service_root,
  410. cache=None,
  411. timeout=None,
  412. proxy_info=None,
  413. version=None,
  414. base_client_name="",
  415. max_retries=Browser.MAX_RETRIES,
  416. ):
  417. """Root access to a lazr.restful API.
  418. :param credentials: The credentials used to access the service.
  419. :param service_root: The URL to the root of the web service.
  420. :type service_root: string
  421. """
  422. if version is not None:
  423. if service_root[-1] != "/":
  424. service_root += "/"
  425. service_root += str(version)
  426. if service_root[-1] != "/":
  427. service_root += "/"
  428. self._root_uri = URI(service_root)
  429. # Set up data necessary to calculate the User-Agent header.
  430. self._base_client_name = base_client_name
  431. # Get the WADL definition.
  432. self.credentials = authorizer
  433. self._browser = Browser(
  434. self,
  435. authorizer,
  436. cache,
  437. timeout,
  438. proxy_info,
  439. self._user_agent,
  440. max_retries,
  441. )
  442. self._wadl = self._browser.get_wadl_application(self._root_uri)
  443. # Get the root resource.
  444. root_resource = self._wadl.get_resource_by_path("")
  445. bound_root = root_resource.bind(
  446. self._browser.get(root_resource), "application/json"
  447. )
  448. super(ServiceRoot, self).__init__(None, bound_root)
  449. @property
  450. def _user_agent(self):
  451. """The value for the User-Agent header.
  452. This will be something like:
  453. launchpadlib 1.6.1, lazr.restfulclient 1.0.0; application=apport
  454. That is, a string describing lazr.restfulclient and an
  455. optional custom client built on top, and parameters containing
  456. any authorization-specific information that identifies the
  457. user agent (such as the application name).
  458. """
  459. base_portion = "lazr.restfulclient %s" % __version__
  460. if self._base_client_name != "":
  461. base_portion = self._base_client_name + " (" + base_portion + ")"
  462. message = Message()
  463. message["User-Agent"] = base_portion
  464. if self.credentials is not None:
  465. user_agent_params = self.credentials.user_agent_params
  466. for key in sorted(user_agent_params):
  467. value = user_agent_params[key]
  468. message.set_param(key, value, "User-Agent")
  469. return message["User-Agent"]
  470. def httpFactory(self, authorizer, cache, timeout, proxy_info):
  471. return RestfulHttp(authorizer, cache, timeout, proxy_info)
  472. def load(self, url):
  473. """Load a resource given its URL."""
  474. parsed = urlparse(url)
  475. if parsed.scheme == "":
  476. # This is a relative URL. Make it absolute by joining
  477. # it with the service root resource.
  478. if url[:1] == "/":
  479. url = url[1:]
  480. url = str(self._root_uri.append(url))
  481. document = self._browser.get(url)
  482. if isinstance(document, binary_type):
  483. document = document.decode("utf-8")
  484. try:
  485. representation = loads(document)
  486. except ValueError:
  487. raise ValueError("%s doesn't serve a JSON document." % url)
  488. type_link = representation.get("resource_type_link")
  489. if type_link is None:
  490. raise ValueError(
  491. "Couldn't determine the resource type of %s." % url
  492. )
  493. resource_type = self._root._wadl.get_resource_type(type_link)
  494. wadl_resource = WadlResource(self._root._wadl, url, resource_type.tag)
  495. return self._create_bound_resource(
  496. self._root,
  497. wadl_resource,
  498. representation,
  499. "application/json",
  500. representation_needs_processing=False,
  501. )
  502. class NamedOperation(RestfulBase):
  503. """A class for a named operation to be invoked with GET or POST."""
  504. def __init__(self, root, resource, wadl_method):
  505. """Initialize with respect to a WADL Method object"""
  506. self.root = root
  507. self.resource = resource
  508. self.wadl_method = wadl_method
  509. def __call__(self, *args, **kwargs):
  510. """Invoke the method and process the result."""
  511. if len(args) > 0:
  512. raise TypeError("Method must be called with keyword args.")
  513. http_method = self.wadl_method.name
  514. args = self._transform_resources_to_links(kwargs)
  515. request = self.wadl_method.request
  516. if http_method in ("get", "head", "delete"):
  517. params = request.query_params
  518. else:
  519. definition = request.get_representation_definition(
  520. "multipart/form-data"
  521. )
  522. if definition is None:
  523. definition = request.get_representation_definition(
  524. "application/x-www-form-urlencoded"
  525. )
  526. assert definition is not None, (
  527. "A POST named operation must define a multipart or "
  528. "form-urlencoded request representation."
  529. )
  530. params = definition.params(self.resource._wadl_resource)
  531. send_as_is_params = {
  532. param.name
  533. for param in params
  534. if param.type == "binary" or len(param.options) > 0
  535. }
  536. for key, value in args.items():
  537. # Certain parameter values should not be JSON-encoded:
  538. # binary parameters (because they can't be JSON-encoded)
  539. # and option values (because JSON-encoding them will screw
  540. # up wadllib's parameter validation). The option value thing
  541. # is a little hacky, but it's the best solution for now.
  542. if key not in send_as_is_params:
  543. args[key] = dumps(value, cls=DatetimeJSONEncoder)
  544. if http_method in ("get", "head", "delete"):
  545. url = self.wadl_method.build_request_url(**args)
  546. in_representation = ""
  547. extra_headers = {}
  548. else:
  549. url = self.wadl_method.build_request_url()
  550. (
  551. media_type,
  552. in_representation,
  553. ) = self.wadl_method.build_representation(**args)
  554. extra_headers = {"Content-type": media_type}
  555. # Pass uppercase method names to httplib2, as that is what it works
  556. # with. If you pass a lowercase method name to httplib then it doesn't
  557. # consider it to be a GET, PUT, etc., and so will do things like not
  558. # cache. Wadl Methods return their method lower cased, which is how it
  559. # is compared in this method, but httplib2 expects the opposite, hence
  560. # the .upper() call.
  561. response, content = self.root._browser._request(
  562. url,
  563. in_representation,
  564. http_method.upper(),
  565. extra_headers=extra_headers,
  566. )
  567. if response.status == 201:
  568. return self._handle_201_response(url, response, content)
  569. else:
  570. if http_method == "post":
  571. # The method call probably modified this resource in
  572. # an unknown way. If it moved to a new location, reload it or
  573. # else just refresh its representation.
  574. if response.status == 301:
  575. url = response["location"]
  576. response, content = self.root._browser._request(url)
  577. else:
  578. self.resource.lp_refresh()
  579. return self._handle_200_response(url, response, content)
  580. def _handle_201_response(self, url, response, content):
  581. """Handle the creation of a new resource by fetching it."""
  582. wadl_response = self.wadl_method.response.bind(
  583. HeaderDictionary(response)
  584. )
  585. wadl_parameter = wadl_response.get_parameter("Location")
  586. wadl_resource = wadl_parameter.linked_resource
  587. # Fetch a representation of the new resource.
  588. response, content = self.root._browser._request(wadl_resource.url)
  589. # Return an instance of the appropriate lazr.restful
  590. # Resource subclass.
  591. return Resource._create_bound_resource(
  592. self.root, wadl_resource, content, response["content-type"]
  593. )
  594. def _handle_200_response(self, url, response, content):
  595. """Process the return value of an operation."""
  596. content_type = response["content-type"]
  597. # Process the returned content, assuming we know how.
  598. response_definition = self.wadl_method.response
  599. representation_definition = (
  600. response_definition.get_representation_definition(content_type)
  601. )
  602. if representation_definition is None:
  603. # The operation returned a document with nothing
  604. # special about it.
  605. if content_type == self.JSON_MEDIA_TYPE:
  606. if isinstance(content, binary_type):
  607. content = content.decode("utf-8")
  608. return loads(content)
  609. # We don't know how to process the content.
  610. return content
  611. # The operation returned a representation of some
  612. # resource. Instantiate a Resource object for it.
  613. if isinstance(content, binary_type):
  614. content = content.decode("utf-8")
  615. document = loads(content)
  616. if document is None:
  617. # The operation returned a null value.
  618. return document
  619. if "self_link" in document and "resource_type_link" in document:
  620. # The operation returned an entry. Use the self_link and
  621. # resource_type_link of the entry representation to build
  622. # a Resource object of the appropriate type. That way this
  623. # object will support all of the right named operations.
  624. url = document["self_link"]
  625. resource_type = self.root._wadl.get_resource_type(
  626. document["resource_type_link"]
  627. )
  628. wadl_resource = WadlResource(
  629. self.root._wadl, url, resource_type.tag
  630. )
  631. else:
  632. # The operation returned a collection. It's probably an ad
  633. # hoc collection that doesn't correspond to any resource
  634. # type. Instantiate it as a resource backed by the
  635. # representation type defined in the return value, instead
  636. # of a resource type tag.
  637. representation_definition = (
  638. representation_definition.resolve_definition()
  639. )
  640. wadl_resource = WadlResource(
  641. self.root._wadl, url, representation_definition.tag
  642. )
  643. return Resource._create_bound_resource(
  644. self.root,
  645. wadl_resource,
  646. document,
  647. content_type,
  648. representation_needs_processing=False,
  649. representation_definition=representation_definition,
  650. )
  651. def _get_external_param_name(self, param_name):
  652. """Named operation parameter names are sent as is."""
  653. return param_name
  654. class Entry(Resource):
  655. """A class for an entry-type resource that can be updated with PATCH."""
  656. def __init__(self, root, wadl_resource):
  657. super(Entry, self).__init__(root, wadl_resource)
  658. # Initialize this here in a semi-magical way so as to stop a
  659. # particular infinite loop that would follow. Setting
  660. # self._dirty_attributes would call __setattr__(), which would
  661. # turn around immediately and get self._dirty_attributes. If
  662. # this latter was not in the instance dictionary, that would
  663. # end up calling __getattr__(), which would again reference
  664. # self._dirty_attributes. This is where the infloop would
  665. # occur. Poking this directly into self.__dict__ means that
  666. # the check for self._dirty_attributes won't call __getattr__(),
  667. # breaking the cycle.
  668. self.__dict__["_dirty_attributes"] = {}
  669. super(Entry, self).__init__(root, wadl_resource)
  670. def __repr__(self):
  671. """Return the WADL resource type and the URL to the resource."""
  672. return "<%s at %s>" % (
  673. URI(self.resource_type_link).fragment,
  674. self.self_link,
  675. )
  676. def lp_delete(self):
  677. """Delete the resource."""
  678. return self._root._browser.delete(URI(self.self_link))
  679. def __str__(self):
  680. """Return the URL to the resource."""
  681. return self.self_link
  682. def __getattr__(self, name):
  683. """Try to retrive a parameter of the given name."""
  684. if name != "_dirty_attributes":
  685. if name in self._dirty_attributes:
  686. return self._dirty_attributes[name]
  687. return super(Entry, self).__getattr__(name)
  688. def __setattr__(self, name, value):
  689. """Set the parameter of the given name."""
  690. if not self.lp_has_parameter(name):
  691. raise AttributeError(
  692. "'%s' object has no attribute '%s'"
  693. % (self.__class__.__name__, name)
  694. )
  695. self._dirty_attributes[name] = value
  696. def __eq__(self, other):
  697. """Equality operator.
  698. Two entries are the same if their self_link and http_etag
  699. attributes are the same, and if their dirty attribute dicts
  700. contain the same values.
  701. """
  702. return (
  703. other is not None
  704. and self.self_link == other.self_link
  705. and self.http_etag == other.http_etag
  706. and self._dirty_attributes == other._dirty_attributes
  707. )
  708. def lp_refresh(self, new_url=None):
  709. """Update this resource's representation."""
  710. etag = getattr(self, "http_etag", None)
  711. super(Entry, self).lp_refresh(new_url, etag)
  712. self._dirty_attributes.clear()
  713. def lp_save(self):
  714. """Save changes to the entry."""
  715. representation = self._transform_resources_to_links(
  716. self._dirty_attributes
  717. )
  718. # If the entry contains an ETag, set the If-Match header
  719. # to that value.
  720. headers = {}
  721. etag = getattr(self, "http_etag", None)
  722. if etag is not None:
  723. headers["If-Match"] = etag
  724. # PATCH the new representation to the 'self' link. It's possible that
  725. # this will cause the object to be permanently moved. Catch that
  726. # exception and refresh our representation.
  727. response, content = self._root._browser.patch(
  728. URI(self.self_link), representation, headers
  729. )
  730. if response.status == 301:
  731. self.lp_refresh(response["location"])
  732. self._dirty_attributes.clear()
  733. content_type = response["content-type"]
  734. if response.status == 209 and content_type == self.JSON_MEDIA_TYPE:
  735. # The server sent back a new representation of the object.
  736. # Use it in preference to the existing representation.
  737. if isinstance(content, binary_type):
  738. content = content.decode("utf-8")
  739. new_representation = loads(content)
  740. self._wadl_resource.representation = new_representation
  741. self._wadl_resource.media_type = content_type
  742. class Collection(Resource):
  743. """A collection-type resource that supports pagination."""
  744. def __init__(self, root, wadl_resource):
  745. """Create a collection object."""
  746. super(Collection, self).__init__(root, wadl_resource)
  747. def __len__(self):
  748. """The number of items in the collection.
  749. :return: length of the collection
  750. :rtype: int
  751. """
  752. total_size = self.total_size
  753. if isinstance(total_size, int):
  754. # The size was a number present in the collection
  755. # representation.
  756. return total_size
  757. elif isinstance(total_size, ScalarValue):
  758. # The size was linked to from the collection representation,
  759. # not directly present.
  760. return total_size.value
  761. else:
  762. raise TypeError("collection size is not available")
  763. def __iter__(self):
  764. """Iterate over the items in the collection.
  765. :return: iterator
  766. :rtype: sequence of `Entry`
  767. """
  768. self._ensure_representation()
  769. current_page = self._wadl_resource.representation
  770. while True:
  771. for resource in self._convert_dicts_to_entries(
  772. current_page.get("entries", {})
  773. ):
  774. yield resource
  775. next_link = current_page.get("next_collection_link")
  776. if next_link is None:
  777. break
  778. next_get = self._root._browser.get(URI(next_link))
  779. if isinstance(next_get, binary_type):
  780. next_get = next_get.decode("utf-8")
  781. current_page = loads(next_get)
  782. def __getitem__(self, key):
  783. """Look up a slice, or a subordinate resource by index.
  784. To discourage situations where a lazr.restful client fetches
  785. all of an enormous list, all collection slices must have a
  786. definitive end point. For performance reasons, all collection
  787. slices must be indexed from the start of the list rather than
  788. the end.
  789. """
  790. if isinstance(key, slice):
  791. return self._get_slice(key)
  792. else:
  793. # Look up a single item by its position in the list.
  794. found_slice = self._get_slice(slice(key, key + 1))
  795. if len(found_slice) != 1:
  796. raise IndexError("list index out of range")
  797. return found_slice[0]
  798. def _get_slice(self, slice):
  799. """Retrieve a slice of a collection."""
  800. start = slice.start or 0
  801. stop = slice.stop
  802. if start < 0:
  803. raise ValueError(
  804. "Collection slices must have a nonnegative " "start point."
  805. )
  806. if stop < 0:
  807. raise ValueError(
  808. "Collection slices must have a definite, "
  809. "nonnegative end point."
  810. )
  811. existing_representation = self._wadl_resource.representation
  812. if existing_representation is not None and start < len(
  813. existing_representation["entries"]
  814. ):
  815. # An optimization: the first page of entries has already
  816. # been loaded. This can happen if this collection is the
  817. # return value of a named operation, or if the client did
  818. # something like check the length of the collection.
  819. #
  820. # Either way, we've already made an HTTP request and
  821. # gotten some entries back. The client has requested a
  822. # slice that includes some of the entries we already have.
  823. # In the best case, we can fulfil the slice immediately,
  824. # without making another HTTP request.
  825. #
  826. # Even if we can't fulfil the entire slice, we can get one
  827. # or more objects from the first page and then have fewer
  828. # objects to retrieve from the server later. This saves us
  829. # time and bandwidth, and it might let us save a whole
  830. # HTTP request.
  831. entry_page = existing_representation["entries"]
  832. first_page_size = len(entry_page)
  833. entry_dicts = entry_page[start:stop]
  834. page_url = existing_representation.get("next_collection_link")
  835. else:
  836. # No part of this collection has been loaded yet, or the
  837. # slice starts beyond the part that has been loaded. We'll
  838. # use our secret knowledge of lazr.restful to set a value for
  839. # the ws.start variable. That way we start reading entries
  840. # from the first one we want.
  841. first_page_size = None
  842. entry_dicts = []
  843. page_url = self._with_url_query_variable_set(
  844. self._wadl_resource.url, "ws.start", start
  845. )
  846. desired_size = stop - start
  847. more_needed = desired_size - len(entry_dicts)
  848. # Iterate over pages until we have the correct number of entries.
  849. while more_needed > 0 and page_url is not None:
  850. page_get = self._root._browser.get(page_url)
  851. if isinstance(page_get, binary_type):
  852. page_get = page_get.decode("utf-8")
  853. representation = loads(page_get)
  854. current_page_entries = representation["entries"]
  855. entry_dicts += current_page_entries[:more_needed]
  856. more_needed = desired_size - len(entry_dicts)
  857. page_url = representation.get("next_collection_link")
  858. if page_url is None:
  859. # We've gotten the entire collection; there are no
  860. # more entries.
  861. break
  862. if first_page_size is None:
  863. first_page_size = len(current_page_entries)
  864. if more_needed > 0 and more_needed < first_page_size:
  865. # An optimization: it's likely that we need less than
  866. # a full page of entries, because the number we need
  867. # is less than the size of the first page we got.
  868. # Instead of requesting a full-sized page, we'll
  869. # request only the number of entries we think we'll
  870. # need. If we're wrong, there's no problem; we'll just
  871. # keep looping.
  872. page_url = self._with_url_query_variable_set(
  873. page_url, "ws.size", more_needed
  874. )
  875. if slice.step is not None:
  876. entry_dicts = entry_dicts[:: slice.step]
  877. # Convert entry_dicts into a list of Entry objects.
  878. return [
  879. resource
  880. for resource in self._convert_dicts_to_entries(entry_dicts)
  881. ]
  882. def _convert_dicts_to_entries(self, entries):
  883. """Convert dictionaries describing entries to Entry objects.
  884. The dictionaries come from the 'entries' field of the JSON
  885. dictionary you get when you GET a page of a collection. Each
  886. dictionary is the same as you'd get if you sent a GET request
  887. to the corresponding entry resource. So each of these
  888. dictionaries can be treated as a preprocessed representation
  889. of an entry resource, and turned into an Entry instance.
  890. :yield: A sequence of Entry instances.
  891. """
  892. for entry_dict in entries:
  893. resource_url = entry_dict["self_link"]
  894. resource_type_link = entry_dict["resource_type_link"]
  895. wadl_application = self._wadl_resource.application
  896. resource_type = wadl_application.get_resource_type(
  897. resource_type_link
  898. )
  899. resource = WadlResource(
  900. self._wadl_resource.application,
  901. resource_url,
  902. resource_type.tag,
  903. )
  904. yield Resource._create_bound_resource(
  905. self._root, resource, entry_dict, self.JSON_MEDIA_TYPE, False
  906. )
  907. def _with_url_query_variable_set(self, url, variable, new_value):
  908. """A helper method to set a query variable in a URL."""
  909. uri = URI(url)
  910. if uri.query is None:
  911. params = {}
  912. else:
  913. params = parse_qs(uri.query)
  914. params[variable] = str(new_value)
  915. uri.query = urlencode(params, True)
  916. return str(uri)
  917. class CollectionWithKeyBasedLookup(Collection):
  918. """A collection-type resource that supports key-based lookup.
  919. This collection can be sliced, but any single index passed into
  920. __getitem__ will be treated as a custom lookup key.
  921. """
  922. def __getitem__(self, key):
  923. """Look up a slice, or a subordinate resource by unique ID."""
  924. if isinstance(key, slice):
  925. return super(CollectionWithKeyBasedLookup, self).__getitem__(key)
  926. try:
  927. url = self._get_url_from_id(key)
  928. except NotImplementedError:
  929. raise TypeError("unsubscriptable object")
  930. if url is None:
  931. raise KeyError(key)
  932. shim_resource = self(key)
  933. try:
  934. shim_resource._ensure_representation()
  935. except HTTPError as e:
  936. if e.response.status == 404:
  937. raise KeyError(key)
  938. else:
  939. raise
  940. return shim_resource
  941. def __call__(self, key):
  942. """Retrieve a member from this collection without looking it up."""
  943. try:
  944. url = self._get_url_from_id(key)
  945. except NotImplementedError:
  946. raise TypeError("unsubscriptable object")
  947. if url is None:
  948. raise ValueError(key)
  949. if self.collection_of is not None:
  950. # We know what kind of resource is at the other end of the
  951. # URL. There's no need to actually fetch that URL until
  952. # the user demands it. If the user is invoking a named
  953. # operation on this object rather than fetching its data,
  954. # this will save us one round trip.
  955. representation = None
  956. resource_type_link = urljoin(
  957. self._root._wadl.markup_url, "#" + self.collection_of
  958. )
  959. else:
  960. # We don't know what kind of resource this is. Either the
  961. # subclass wasn't programmed with this knowledge, or
  962. # there's simply no way to tell without going to the
  963. # server, because the collection contains more than one
  964. # kind of resource. The only way to know for sure is to
  965. # retrieve a representation of the resource and see how
  966. # the resource describes itself.
  967. try:
  968. url_get = self._root._browser.get(url)
  969. if isinstance(url_get, binary_type):
  970. url_get = url_get.decode("utf-8")
  971. representation = loads(url_get)
  972. except HTTPError as error:
  973. # There's no resource corresponding to the given ID.
  974. if error.response.status == 404:
  975. raise KeyError(key)
  976. raise
  977. # We know that every lazr.restful resource has a
  978. # 'resource_type_link' in its representation.
  979. resource_type_link = representation["resource_type_link"]
  980. resource = WadlResource(self._root._wadl, url, resource_type_link)
  981. return self._create_bound_resource(
  982. self._root,
  983. resource,
  984. representation=representation,
  985. representation_needs_processing=False,
  986. )
  987. # If provided, this should be a string designating the ID of a
  988. # resource_type from a specific service's WADL file.
  989. collection_of = None
  990. def _get_url_from_id(self, key):
  991. """Transform the unique ID of an object into its URL."""
  992. raise NotImplementedError()
  993. class HostedFileBuffer(BytesIO):
  994. """The contents of a file hosted by a lazr.restful service."""
  995. def __init__(self, hosted_file, mode, content_type=None, filename=None):
  996. self.url = hosted_file._wadl_resource.url
  997. if mode == "r":
  998. if content_type is not None:
  999. raise ValueError(
  1000. "Files opened for read access can't "
  1001. "specify content_type."
  1002. )
  1003. if filename is not None:
  1004. raise ValueError(
  1005. "Files opened for read access can't " "specify filename."
  1006. )
  1007. response, value = hosted_file._root._browser.get(
  1008. self.url, return_response=True
  1009. )
  1010. content_type = response["content-type"]
  1011. last_modified = response.get("last-modified")
  1012. # The Content-Location header contains the URL of the file
  1013. # hosted by the web service. We happen to know that the
  1014. # final component of the URL is the name of the uploaded
  1015. # file.
  1016. content_location = response["content-location"]
  1017. path = urlparse(content_location)[2]
  1018. filename = unquote(path.split("/")[-1])
  1019. elif mode == "w":
  1020. value = b""
  1021. if content_type is None:
  1022. raise ValueError(
  1023. "Files opened for write access must "
  1024. "specify content_type."
  1025. )
  1026. if filename is None:
  1027. raise ValueError(
  1028. "Files opened for write access must " "specify filename."
  1029. )
  1030. last_modified = None
  1031. else:
  1032. raise ValueError("Invalid mode. Supported modes are: r, w")
  1033. self.hosted_file = hosted_file
  1034. self.mode = mode
  1035. self.content_type = content_type
  1036. self.filename = filename
  1037. self.last_modified = last_modified
  1038. BytesIO.__init__(self, value)
  1039. def close(self):
  1040. if self.mode == "w":
  1041. disposition = 'attachment; filename="%s"' % self.filename
  1042. self.hosted_file._root._browser.put(
  1043. self.url,
  1044. self.getvalue(),
  1045. self.content_type,
  1046. {"Content-Disposition": disposition},
  1047. )
  1048. BytesIO.close(self)
  1049. def write(self, b):
  1050. BytesIO.write(self, b)