Ejemplo n.º 1
0
    def get_expand(self, prop_or_name):
        """Get a Model instance associated with an expanded property.

    Args:
      prop_or_name: Property or str, The expandable property (or property name)
          that should be expanded.

    Returns:
      If expanded data is present, an instance of the Model listed in the
      property's `expands_to` attribute.
      Else, None.

    Raises:
      PropertyError: An invalid or non-expandable property was provided OR the
          expands_to attribute on the property did not correspond to a known
          Model kind.
    """
        prop = self._get_and_validate_property(prop_or_name,
                                               require_expandable=True)

        expand_cls = self._KIND_MAP.get(prop.expands_to)
        if expand_cls is None:
            raise excs.PropertyError('Cannot expand to unknown Model "%s"' %
                                     prop.expands_to)

        expanded_properties = (key for key in self._obj_dict.keys()
                               if key.startswith(prop.name + '_'))
        if any(expanded_properties):
            return expand_cls.from_dict(self._obj_dict, prefix=prop.name)
        else:
            return None
Ejemplo n.º 2
0
    def _get_and_validate_property(cls,
                                   prop_or_name,
                                   require_updatable=False,
                                   require_expandable=False):
        """Converts the arg to a Property and ensures it's valid.

    Args:
      prop_or_name: Property or str, If str, it should be the name of a property
          on this Model. If Property, the function will verify that it belongs
          to this Model class.
      require_updatable: bool, Whether to perform an additional validation step
          to ensure the returned property is able to be updated.
      require_expandable: bool, Whether to perform an additional validation step
          to ensure the returned property is able to be expanded.

    Returns:
      The Property object provided or the one associated with the name that was
      provided.

    Raises:
      PropertyError: Some aspect of validation failed.
    """
        if isinstance(prop_or_name, Property):
            prop = prop_or_name
        else:
            prop = cls._PROPERTIES.get(prop_or_name)
            if prop is None:
                raise excs.PropertyError(
                    'Unknown property: {}'.format(prop_or_name))

        if not cls.is_valid_property(prop):
            raise excs.PropertyError('{} cannot be used with {}'.format(
                prop, cls.__name__))
        elif require_updatable and not prop.updatable:
            raise excs.PropertyError(
                'Property {} may not be updated'.format(prop))
        elif require_expandable and not prop.expandable:
            raise excs.PropertyError(
                'Property {} may not be expanded'.format(prop))

        return prop