Skip to content

Architecture

Drawpyo provides two high level classes to define critical methods and attributes for all exportable Draw.io objects. Primarily they define the parent and id attributes as well as a series of methods and properties for generating XML and style strings.


XMLBase

XMLBase is the base class for all exportable objects in drawpyo. This class defines a few useful properties that drawpyo needs to use to generate a Draw.io file.

Source code in src/drawpyo/xml_base.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
class XMLBase:
    """
    XMLBase is the base class for all exportable objects in drawpyo. This class defines a few useful properties that drawpyo needs to use to generate a Draw.io file.
    """

    def __init__(self, **kwargs):
        self._id = kwargs.get("id", id(self))
        self.xml_class = kwargs.get("xml_class", "xml_tag")

        # There's only one situation where XMLBase is called directly: to
        # create the two empty mxCell objects at the beginning of every
        # Draw.io diagram. The following declarations should be overwritten
        # in every other use case.
        self.xml_parent = kwargs.get("xml_parent", None)

    @property
    def id(self):
        """
        id is a unique identifier. Draw.io generated diagrams use an ID many more characters but the app isn't picky when parsing so drawpyo just uses Python's built-in id() function as it guarantees unique identifiers.

        Returns:
            int: A unique identifier for the Draw.io object
        """
        return self._id

    @property
    def attributes(self):
        """
        The most basic attributes of a Draw.io object. Extended by subclasses.

        Returns:
            dict: A dict containing an 'id' and 'xml_parent' object.
        """
        return {"id": self.id, "parent": self.xml_parent}

    ###########################################################
    # XML Tags
    ###########################################################

    @property
    def xml_open_tag(self):
        """
        The open tag contains the name of the object but also the attribute tags. This property function concatenates all the attributes in the class along with the opening and closing angle brackets and returns them as a string.

        Example:
        <class_name attribute_name=attribute_value>

        Returns:
            str: The opening tag of the object with all the attributes.
        """
        open_tag = "<" + self.xml_class
        for att, value in self.attributes.items():
            if value is not None:
                xml_parameter = self.xml_ify(str(value))
                open_tag = open_tag + " " + att + '="' + xml_parameter + '"'
        return open_tag + ">"

    @property
    def xml_close_tag(self):
        """
        The closing tag contains the name of the object wrapped in angle brackets.

        Example:
        </class_name>

        Returns:
            str: The closing tag of the object with all the attributes.
        """
        return "</{0}>".format(self.xml_class)

    @property
    def xml(self):
        """
        All drawpyo exportable classes contain an xml property that returns the formatted string of their XML output.

        This default version of the function assumes no inner value so it just returns the opening tag closed with a '/>'. Subclasses that require more printing overload this function with their own implementation.

        Example:
        <class_name attribute_name=attribute_value/>

        Returns:
            str: A single XML tag containing the object name, style attributes, and a closer.
        """
        return self.xml_open_tag[:-1] + " />"

    def xml_ify(self, parameter_string):
        return self.translate_txt(parameter_string, xmlize)

    @staticmethod
    def translate_txt(string, replacement_dict):
        new_str = ""
        for char in string:
            if char in replacement_dict:
                new_str = new_str + replacement_dict[char]
            else:
                new_str = new_str + char
        return new_str

attributes property

The most basic attributes of a Draw.io object. Extended by subclasses.

Returns:

Name Type Description
dict

A dict containing an 'id' and 'xml_parent' object.

id property

id is a unique identifier. Draw.io generated diagrams use an ID many more characters but the app isn't picky when parsing so drawpyo just uses Python's built-in id() function as it guarantees unique identifiers.

Returns:

Name Type Description
int

A unique identifier for the Draw.io object

xml property

All drawpyo exportable classes contain an xml property that returns the formatted string of their XML output.

This default version of the function assumes no inner value so it just returns the opening tag closed with a '/>'. Subclasses that require more printing overload this function with their own implementation.

Example:

Returns:

Name Type Description
str

A single XML tag containing the object name, style attributes, and a closer.

xml_close_tag property

The closing tag contains the name of the object wrapped in angle brackets.

Example:

Returns:

Name Type Description
str

The closing tag of the object with all the attributes.

xml_open_tag property

The open tag contains the name of the object but also the attribute tags. This property function concatenates all the attributes in the class along with the opening and closing angle brackets and returns them as a string.

Example:

Returns:

Name Type Description
str

The opening tag of the object with all the attributes.


DiagramBase

Bases: XMLBase

This class is the base for all diagram objects to inherit from. It defines some general creation methods and properties to make diagram objects printable and useful.

Source code in src/drawpyo/diagram/base_diagram.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
class DiagramBase(XMLBase):
    """
    This class is the base for all diagram objects to inherit from. It defines some general creation methods and properties to make diagram objects printable and useful.
    """

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._style_attributes = ["html"]
        self.page = kwargs.get("page", None)
        self.xml_parent = kwargs.get("xml_parent", None)

    @classmethod
    def create_from_library(cls, library, obj):
        return cls

    # XML_parent property
    @property
    def xml_parent_id(self):
        if self.xml_parent is not None:
            return self.xml_parent.id
        else:
            return 1

    # Parent object linking
    @property
    def xml_parent(self):
        return self._xml_parent

    @xml_parent.setter
    def xml_parent(self, p):
        if p is not None:
            p.add_object(self)
            self._xml_parent = p
        else:
            self._xml_parent = None

    @xml_parent.deleter
    def xml_parent(self):
        self._xml_parent.remove_object(self)
        self._xml_parent = None

    # Page property
    @property
    def page_id(self):
        if self.page is not None:
            return self.page.id
        else:
            return 1

    # page object linking
    @property
    def page(self):
        return self._page

    @page.setter
    def page(self, p):
        if p is not None:
            p.add_object(self)
            self._page = p
        else:
            self._page = None

    @page.deleter
    def page(self):
        self._page.remove_object(self)
        self._page = None

    def add_object(self, obj):
        self.page.add_object(obj)

    ###########################################################
    # Style properties
    ###########################################################
    def add_style_attribute(self, style_attr):
        if style_attr not in self._style_attributes:
            self._style_attributes.append(style_attr)

    @property
    def style_attributes(self):
        """
        The style attributes are the list of style tags that should be printed into the style XML attribute. This is a subset of the attributes defined on the object method.

        Returns:
            list: A list of the names of the style_attributes.
        """
        return self._style_attributes

    @style_attributes.setter
    def style_attributes(self, value):
        self._style_attributes = value

    @property
    def style(self):
        """
        This function returns the style string of the object to be appended into the style XML attribute.

        First it searches the object properties called out in
        self.style_attributes. If the property is initialized to something
        that isn't None or an empty string, it will add it. Otherwise it
        searches the base_style defined by the object template.

        Returns:
            str: The style string of the object.

        """

        style_str = ""
        if (
            hasattr(self, "baseStyle")
            and getattr(self, "baseStyle") is not None
            and getattr(self, "baseStyle") != ""
        ):
            style_str = getattr(self, "baseStyle") + ";"

        # Add style attributes
        for attribute in self.style_attributes:
            if hasattr(self, attribute) and getattr(self, attribute) is not None:
                attr_val = getattr(self, attribute)
                # reformat different datatypes to strings
                if isinstance(attr_val, bool):
                    attr_val = format(attr_val * 1)
                style_str = style_str + "{0}={1};".format(attribute, attr_val)

        # Add style objects
        if hasattr(self, "text_format") and self.text_format is not None:
            style_str = style_str + self.text_format.style
        return style_str

    def _add_and_set_style_attrib(self, attrib, value):
        if hasattr(self, attrib):
            setattr(self, attrib, value)
        else:
            setattr(self, attrib, value)
            self.add_style_attribute(attrib)

    def apply_style_string(self, style_str):
        """
        This function will apply a passed in style string to the object. This style string can be obtained from the Draw.io app by selecting Edit Style from the context menu of any object. This function will iterate through the attributes in the style string and assign the corresponding property the value.

        Args:
            style_str (str): A Draw.io style string
        """
        for attrib in style_str.split(";"):
            if attrib == "":
                pass
            elif "=" in attrib:
                a_name = attrib.split("=")[0]
                a_value = attrib.split("=")[1]
                if a_value.isdigit():
                    if "." in a_value:
                        a_value = float(a_value)
                    else:
                        a_value = int(a_value)
                elif a_value == "True" or a_value == "False":
                    a_value = bool(a_value)

                self._add_and_set_style_attrib(a_name, a_value)
            else:
                self.baseStyle = attrib

    def _apply_style_from_template(self, template):
        for attrib in template.style_attributes:
            value = getattr(template, attrib)
            self._add_and_set_style_attrib(attrib, value)

    def apply_attribute_dict(self, attr_dict):
        """
        This function takes in a dictionary of attributes and applies them
        to the object. These attributes can be style or properties. If the
        attribute isn't already defined as a property of the class it's
        assumed to be a style attribute. It will then be added as a property
        and also appended to the .style_attributes list.

        Parameters
        ----------
        attr_dict : dict
            A dictionary of attributes to set or add to the object.

        Returns
        -------
        None.

        """
        for attr, val in attr_dict.items():
            self._add_and_set_style_attrib(attr, val)

    @classmethod
    def from_style_string(cls, style_string):
        """
        This classmethod allows the intantiation of an object from a style
        string. This is useful since Draw.io allows copying the style string
        out of an object in their UI. This string can then be copied into the
        Python environment and further objects created that match the style.

        Args:
            style_string (str): A Draw.io style string

        Returns:
            BaseDiagram: A BaseDiagram or subclass instantiated with the style from the Draw.io string
        """
        new_obj = cls()
        new_obj.apply_style_string(style_string)
        return new_obj

style property

This function returns the style string of the object to be appended into the style XML attribute.

First it searches the object properties called out in self.style_attributes. If the property is initialized to something that isn't None or an empty string, it will add it. Otherwise it searches the base_style defined by the object template.

Returns:

Name Type Description
str

The style string of the object.

style_attributes property writable

The style attributes are the list of style tags that should be printed into the style XML attribute. This is a subset of the attributes defined on the object method.

Returns:

Name Type Description
list

A list of the names of the style_attributes.

apply_attribute_dict(attr_dict)

This function takes in a dictionary of attributes and applies them to the object. These attributes can be style or properties. If the attribute isn't already defined as a property of the class it's assumed to be a style attribute. It will then be added as a property and also appended to the .style_attributes list.

Parameters

attr_dict : dict A dictionary of attributes to set or add to the object.

Returns

None.

Source code in src/drawpyo/diagram/base_diagram.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def apply_attribute_dict(self, attr_dict):
    """
    This function takes in a dictionary of attributes and applies them
    to the object. These attributes can be style or properties. If the
    attribute isn't already defined as a property of the class it's
    assumed to be a style attribute. It will then be added as a property
    and also appended to the .style_attributes list.

    Parameters
    ----------
    attr_dict : dict
        A dictionary of attributes to set or add to the object.

    Returns
    -------
    None.

    """
    for attr, val in attr_dict.items():
        self._add_and_set_style_attrib(attr, val)

apply_style_string(style_str)

This function will apply a passed in style string to the object. This style string can be obtained from the Draw.io app by selecting Edit Style from the context menu of any object. This function will iterate through the attributes in the style string and assign the corresponding property the value.

Parameters:

Name Type Description Default
style_str str

A Draw.io style string

required
Source code in src/drawpyo/diagram/base_diagram.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def apply_style_string(self, style_str):
    """
    This function will apply a passed in style string to the object. This style string can be obtained from the Draw.io app by selecting Edit Style from the context menu of any object. This function will iterate through the attributes in the style string and assign the corresponding property the value.

    Args:
        style_str (str): A Draw.io style string
    """
    for attrib in style_str.split(";"):
        if attrib == "":
            pass
        elif "=" in attrib:
            a_name = attrib.split("=")[0]
            a_value = attrib.split("=")[1]
            if a_value.isdigit():
                if "." in a_value:
                    a_value = float(a_value)
                else:
                    a_value = int(a_value)
            elif a_value == "True" or a_value == "False":
                a_value = bool(a_value)

            self._add_and_set_style_attrib(a_name, a_value)
        else:
            self.baseStyle = attrib

from_style_string(style_string) classmethod

This classmethod allows the intantiation of an object from a style string. This is useful since Draw.io allows copying the style string out of an object in their UI. This string can then be copied into the Python environment and further objects created that match the style.

Parameters:

Name Type Description Default
style_string str

A Draw.io style string

required

Returns:

Name Type Description
BaseDiagram

A BaseDiagram or subclass instantiated with the style from the Draw.io string

Source code in src/drawpyo/diagram/base_diagram.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
@classmethod
def from_style_string(cls, style_string):
    """
    This classmethod allows the intantiation of an object from a style
    string. This is useful since Draw.io allows copying the style string
    out of an object in their UI. This string can then be copied into the
    Python environment and further objects created that match the style.

    Args:
        style_string (str): A Draw.io style string

    Returns:
        BaseDiagram: A BaseDiagram or subclass instantiated with the style from the Draw.io string
    """
    new_obj = cls()
    new_obj.apply_style_string(style_string)
    return new_obj