Esempio n. 1
0
    def from_definition(cls, definition):
        """
        Create podpac Node from a dictionary definition.

        Arguments
        ---------
        d : dict
            node definition

        Returns
        -------
        :class:`Node`
            podpac Node

        See Also
        --------
        definition : node definition as a dictionary
        from_json : create podpac node from a JSON definition
        load : create a node from file
        """

        if "podpac_version" in definition and definition["podpac_version"] != podpac.__version__:
            warnings.warn(
                "node definition version mismatch "
                "(this node was created with podpac version '%s', "
                "but your current podpac version is '%s')" % (definition["podpac_version"], podpac.__version__)
            )

        if len(definition) == 0:
            raise ValueError("Invalid definition: definition cannot be empty.")

        # parse node definitions in order
        nodes = OrderedDict()
        for name, d in definition.items():
            if name == "podpac_version":
                continue

            if "node" not in d:
                raise ValueError("Invalid definition for node '%s': 'node' property required" % name)

            # get node class
            module_root = d.get("plugin", "podpac")
            node_string = "%s.%s" % (module_root, d["node"])
            module_name, node_name = node_string.rsplit(".", 1)
            try:
                module = importlib.import_module(module_name)
            except ImportError:
                raise ValueError("Invalid definition for node '%s': no module found '%s'" % (name, module_name))
            try:
                node_class = getattr(module, node_name)
            except AttributeError:
                raise ValueError(
                    "Invalid definition for node '%s': class '%s' not found in module '%s'"
                    % (name, node_name, module_name)
                )

            # parse and configure kwargs
            kwargs = {}
            for k, v in d.get("attrs", {}).items():
                kwargs[k] = v

            for k, v in d.get("inputs", {}).items():
                kwargs[k] = _lookup_input(nodes, name, v)

            for k, v in d.get("lookup_attrs", {}).items():
                kwargs[k] = _lookup_attr(nodes, name, v)

            if "style" in d:
                style_class = getattr(node_class, 'style', Style)
                if isinstance(style_class, tl.TraitType):
                    # Now we actually have to look through the class to see
                    # if there is a custom initializer for style
                    for attr in dir(node_class):
                        atr = getattr(node_class, attr)
                        if not isinstance(atr, tl.traitlets.DefaultHandler) or atr.trait_name != 'style':
                            continue
                        try:
                            style_class = atr(node_class)
                        except Exception as e:
                            # print ("couldn't make style from class", e)
                            try:
                                style_class = atr(node_class())
                            except:
                                # print ("couldn't make style from class instance", e)
                                style_class = style_class.klass
                try:
                    kwargs["style"] = style_class.from_definition(d["style"])
                except Exception as e:
                    kwargs["style"] = Style.from_definition(d["style"])
                    # print ("couldn't make style from inferred style class", e)



            for k in d:
                if k not in ["node", "inputs", "attrs", "lookup_attrs", "plugin", "style"]:
                    raise ValueError("Invalid definition for node '%s': unexpected property '%s'" % (name, k))

            nodes[name] = node_class(**kwargs)

        return list(nodes.values())[-1]
Esempio n. 2
0
    def from_definition(cls, definition):
        """
        Create podpac Node from a dictionary definition.

        Arguments
        ---------
        d : dict
            node definition

        Returns
        -------
        :class:`Node`
            podpac Node

        See Also
        --------
        definition : node definition as a dictionary
        from_json : create podpac node from a JSON definition
        load : create a node from file
        """

        if "podpac_version" in definition and definition[
                "podpac_version"] != podpac.__version__:
            warnings.warn("node definition version mismatch "
                          "(this node was created with podpac version '%s', "
                          "but your current podpac version is '%s')" %
                          (definition["podpac_version"], podpac.__version__))

        if len(definition) == 0:
            raise ValueError("Invalid definition: definition cannot be empty.")

        # parse node definitions in order
        nodes = OrderedDict()
        for name, d in definition.items():
            if name == "podpac_version":
                continue

            if "node" not in d:
                raise ValueError(
                    "Invalid definition for node '%s': 'node' property required"
                    % name)

            # get node class
            module_root = d.get("plugin", "podpac")
            node_string = "%s.%s" % (module_root, d["node"])
            module_name, node_name = node_string.rsplit(".", 1)
            try:
                module = importlib.import_module(module_name)
            except ImportError:
                raise ValueError(
                    "Invalid definition for node '%s': no module found '%s'" %
                    (name, module_name))
            try:
                node_class = getattr(module, node_name)
            except AttributeError:
                raise ValueError(
                    "Invalid definition for node '%s': class '%s' not found in module '%s'"
                    % (name, node_name, module_name))

            # parse and configure kwargs
            kwargs = {}
            for k, v in d.get("attrs", {}).items():
                kwargs[k] = v

            for k, v in d.get("inputs", {}).items():
                kwargs[k] = _lookup_input(nodes, name, v)

            for k, v in d.get("lookup_attrs", {}).items():
                kwargs[k] = _lookup_attr(nodes, name, v)

            if "style" in d:
                kwargs["style"] = Style.from_definition(d["style"])

            for k in d:
                if k not in [
                        "node", "inputs", "attrs", "lookup_attrs", "plugin",
                        "style"
                ]:
                    raise ValueError(
                        "Invalid definition for node '%s': unexpected property '%s'"
                        % (name, k))

            nodes[name] = node_class(**kwargs)

        return list(nodes.values())[-1]