Example #1
0
    def _handle_200_response(self, url, response, content):
        """Process the return value of an operation."""
        content_type = response['content-type']
        # Process the returned content, assuming we know how.
        response_definition = self.wadl_method.response
        representation_definition = (
            response_definition.get_representation_definition(
                content_type))

        if representation_definition is None:
            # The operation returned a document with nothing
            # special about it.
            if content_type == self.JSON_MEDIA_TYPE:
                if isinstance(content, binary_type):
                    content = content.decode('utf-8')
                return loads(content)
            # We don't know how to process the content.
            return content

        # The operation returned a representation of some
        # resource. Instantiate a Resource object for it.
        if isinstance(content, binary_type):
            content = content.decode('utf-8')
        
        document = loads(content)
        if document is None:
            # The operation returned a null value.
            return document
        if "self_link" in document and "resource_type_link" in document:
            # The operation returned an entry. Use the self_link and
            # resource_type_link of the entry representation to build
            # a Resource object of the appropriate type. That way this
            # object will support all of the right named operations.
            url = document["self_link"]
            resource_type = self.root._wadl.get_resource_type(
                document["resource_type_link"])
            wadl_resource = WadlResource(self.root._wadl, url,
                                         resource_type.tag)
        else:
            # The operation returned a collection. It's probably an ad
            # hoc collection that doesn't correspond to any resource
            # type.  Instantiate it as a resource backed by the
            # representation type defined in the return value, instead
            # of a resource type tag.
            representation_definition = (
                representation_definition.resolve_definition())
            wadl_resource = WadlResource(
                self.root._wadl, url, representation_definition.tag)

        return Resource._create_bound_resource(
            self.root, wadl_resource, document, content_type,
            representation_needs_processing=False,
            representation_definition=representation_definition)
Example #2
0
 def load(self, url):
     """Load a resource given its URL."""
     parsed = urlparse(url)
     if parsed.scheme == '':
         # This is a relative URL. Make it absolute by joining
         # it with the service root resource.
         if url[:1] == '/':
             url = url[1:]
         url = str(self._root_uri.append(url))
     document = self._browser.get(url)
     try:
         representation = simplejson.loads(unicode(document))
     except ValueError:
         raise ValueError("%s doesn't serve a JSON document." % url)
     type_link = representation.get("resource_type_link")
     if type_link is None:
         raise ValueError("Couldn't determine the resource type of %s." %
                          url)
     resource_type = self._root._wadl.get_resource_type(type_link)
     wadl_resource = WadlResource(self._root._wadl, url, resource_type.tag)
     return self._create_bound_resource(
         self._root,
         wadl_resource,
         representation,
         'application/json',
         representation_needs_processing=False)
Example #3
0
    def __call__(self, key):
        """Retrieve a member from this collection without looking it up."""

        try:
            url = self._get_url_from_id(key)
        except NotImplementedError:
            raise TypeError("unsubscriptable object")
        if url is None:
            raise ValueError(key)

        if self.collection_of is not None:
            # We know what kind of resource is at the other end of the
            # URL. There's no need to actually fetch that URL until
            # the user demands it. If the user is invoking a named
            # operation on this object rather than fetching its data,
            # this will save us one round trip.
            representation = None
            resource_type_link = urljoin(
                self._root._wadl.markup_url, '#' + self.collection_of)
        else:
            # We don't know what kind of resource this is. Either the
            # subclass wasn't programmed with this knowledge, or
            # there's simply no way to tell without going to the
            # server, because the collection contains more than one
            # kind of resource. The only way to know for sure is to
            # retrieve a representation of the resource and see how
            # the resource describes itself.
            try:
                url_get = self._root._browser.get(url)
                if isinstance(url_get, binary_type):
                    url_get = url_get.decode('utf-8')                
                representation = loads(url_get)
            except HTTPError as error:
                # There's no resource corresponding to the given ID.
                if error.response.status == 404:
                    raise KeyError(key)
                raise
            # We know that every lazr.restful resource has a
            # 'resource_type_link' in its representation.
            resource_type_link = representation['resource_type_link']

        resource = WadlResource(self._root._wadl, url, resource_type_link)
        return self._create_bound_resource(
            self._root, resource, representation=representation,
            representation_needs_processing=False)
Example #4
0
    def _convert_dicts_to_entries(self, entries):
        """Convert dictionaries describing entries to Entry objects.

        The dictionaries come from the 'entries' field of the JSON
        dictionary you get when you GET a page of a collection. Each
        dictionary is the same as you'd get if you sent a GET request
        to the corresponding entry resource. So each of these
        dictionaries can be treated as a preprocessed representation
        of an entry resource, and turned into an Entry instance.

        :yield: A sequence of Entry instances.
        """
        for entry_dict in entries:
            resource_url = entry_dict['self_link']
            resource_type_link = entry_dict['resource_type_link']
            wadl_application = self._wadl_resource.application
            resource_type = wadl_application.get_resource_type(
                resource_type_link)
            resource = WadlResource(self._wadl_resource.application,
                                    resource_url, resource_type.tag)
            yield Resource._create_bound_resource(self._root, resource,
                                                  entry_dict,
                                                  self.JSON_MEDIA_TYPE, False)
Example #5
0
            # kind of resource. The only way to know for sure is to
            # retrieve a representation of the resource and see how
            # the resource describes itself.
            try:
                representation = simplejson.loads(
                    unicode(self._root._browser.get(url)))
            except HTTPError, error:
                # There's no resource corresponding to the given ID.
                if error.response.status == 404:
                    raise KeyError(key)
                raise
            # We know that every lazr.restful resource has a
            # 'resource_type_link' in its representation.
            resource_type_link = representation['resource_type_link']

        resource = WadlResource(self._root._wadl, url, resource_type_link)
        return self._create_bound_resource(
            self._root,
            resource,
            representation=representation,
            representation_needs_processing=False)

    # If provided, this should be a string designating the ID of a
    # resource_type from a specific service's WADL file.
    collection_of = None

    def _get_url_from_id(self, key):
        """Transform the unique ID of an object into its URL."""
        raise NotImplementedError()