File: graph_models.py

package info (click to toggle)
python-django-extensions 4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 2,820 kB
  • sloc: python: 18,601; javascript: 7,354; makefile: 108; xml: 17
file content (486 lines) | stat: -rw-r--r-- 17,929 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
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
111
112
113
114
115
116
117
118
119
120
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# -*- coding: utf-8 -*-
import sys
import json
import os
import tempfile

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.template import loader

from django_extensions.management.modelviz import ModelGraph, generate_dot
from django_extensions.management.utils import signalcommand

try:
    import pygraphviz

    HAS_PYGRAPHVIZ = True
except ImportError:
    HAS_PYGRAPHVIZ = False

try:
    try:
        import pydotplus as pydot
    except ImportError:
        import pydot
    HAS_PYDOT = True
except ImportError:
    HAS_PYDOT = False


def retheme(graph_data, app_style={}):
    if isinstance(app_style, str):
        if os.path.exists(app_style):
            try:
                with open(app_style, "rt") as f:
                    app_style = json.load(f)
            except Exception as e:
                print(f"Invalid app style file {app_style}")
                raise Exception(e)
        else:
            return graph_data

    for gc in graph_data["graphs"]:
        for g in gc:
            if "name" in g:
                for m in g["models"]:
                    app_name = g["app_name"]
                    if app_name in app_style:
                        m["style"] = app_style[app_name]
    return graph_data


class Command(BaseCommand):
    help = "Creates a GraphViz dot file for the specified app names."
    " You can pass multiple app names and they will all be combined into a"
    " single model. Output is usually directed to a dot file."

    can_import_settings = True

    def __init__(self, *args, **kwargs):
        """
        Allow defaults for arguments to be set in settings.GRAPH_MODELS.

        Each argument in self.arguments is a dict where the key is the
        space-separated args and the value is our kwarg dict.

        The default from settings is keyed as the long arg name with '--'
        removed and any '-' replaced by '_'. For example, the default value for
        --disable-fields can be set in settings.GRAPH_MODELS['disable_fields'].
        """
        self.arguments = {
            "--app-style": {
                "action": "store",
                "help": "Path to style json to configure the style per app",
                "dest": "app-style",
                "default": ".app-style.json",
            },
            "--pygraphviz": {
                "action": "store_true",
                "default": False,
                "dest": "pygraphviz",
                "help": "Output graph data as image using PyGraphViz.",
            },
            "--pydot": {
                "action": "store_true",
                "default": False,
                "dest": "pydot",
                "help": "Output graph data as image using PyDot(Plus).",
            },
            "--dot": {
                "action": "store_true",
                "default": False,
                "dest": "dot",
                "help": (
                    "Output graph data as raw DOT (graph description language) "
                    "text data."
                ),
            },
            "--json": {
                "action": "store_true",
                "default": False,
                "dest": "json",
                "help": "Output graph data as JSON",
            },
            "--disable-fields -d": {
                "action": "store_true",
                "default": False,
                "dest": "disable_fields",
                "help": "Do not show the class member fields",
            },
            "--disable-abstract-fields": {
                "action": "store_true",
                "default": False,
                "dest": "disable_abstract_fields",
                "help": "Do not show the class member fields that were inherited",
            },
            "--display-field-choices": {
                "action": "store_true",
                "default": False,
                "dest": "display_field_choices",
                "help": "Display choices instead of field type",
            },
            "--group-models -g": {
                "action": "store_true",
                "default": False,
                "dest": "group_models",
                "help": "Group models together respective to their application",
            },
            "--all-applications -a": {
                "action": "store_true",
                "default": False,
                "dest": "all_applications",
                "help": "Automatically include all applications from INSTALLED_APPS",
            },
            "--output -o": {
                "action": "store",
                "dest": "outputfile",
                "help": (
                    "Render output file. Type of output dependend on file extensions. "
                    "Use png or jpg to render graph to image."
                ),
            },
            "--layout -l": {
                "action": "store",
                "dest": "layout",
                "default": "dot",
                "help": "Layout to be used by GraphViz for visualization. Layouts: "
                "circo dot fdp neato nop nop1 nop2 twopi",
            },
            "--theme -t": {
                "action": "store",
                "dest": "theme",
                "default": "django2018",
                "help": "Theme to use. Supplied are 'original' and 'django2018'. "
                "You can create your own by creating dot templates in "
                "'django_extentions/graph_models/themename/' template directory.",
            },
            "--verbose-names -n": {
                "action": "store_true",
                "default": False,
                "dest": "verbose_names",
                "help": "Use verbose_name of models and fields",
            },
            "--language -L": {
                "action": "store",
                "dest": "language",
                "help": "Specify language used for verbose_name localization",
            },
            "--exclude-columns -x": {
                "action": "store",
                "dest": "exclude_columns",
                "help": "Exclude specific column(s) from the graph. "
                "Can also load exclude list from file.",
            },
            "--exclude-models -X": {
                "action": "store",
                "dest": "exclude_models",
                "help": "Exclude specific model(s) from the graph. Can also load "
                "exclude list from file. Wildcards (*) are allowed.",
            },
            "--include-models -I": {
                "action": "store",
                "dest": "include_models",
                "help": "Restrict the graph to specified models. "
                "Wildcards (*) are allowed.",
            },
            "--inheritance -e": {
                "action": "store_true",
                "default": True,
                "dest": "inheritance",
                "help": "Include inheritance arrows (default)",
            },
            "--no-inheritance -E": {
                "action": "store_false",
                "default": False,
                "dest": "inheritance",
                "help": "Do not include inheritance arrows",
            },
            "--hide-relations-from-fields -R": {
                "action": "store_false",
                "default": True,
                "dest": "relations_as_fields",
                "help": "Do not show relations as fields in the graph.",
            },
            "--relation-fields-only": {
                "action": "store",
                "default": False,
                "dest": "relation_fields_only",
                "help": "Only display fields that are relevant for relations",
            },
            "--disable-sort-fields -S": {
                "action": "store_false",
                "default": True,
                "dest": "sort_fields",
                "help": "Do not sort fields",
            },
            "--hide-edge-labels": {
                "action": "store_true",
                "default": False,
                "dest": "hide_edge_labels",
                "help": "Do not show relations labels in the graph.",
            },
            "--arrow-shape": {
                "action": "store",
                "default": "dot",
                "dest": "arrow_shape",
                "choices": [
                    "box",
                    "crow",
                    "curve",
                    "icurve",
                    "diamond",
                    "dot",
                    "inv",
                    "none",
                    "normal",
                    "tee",
                    "vee",
                ],
                "help": "Arrow shape to use for relations. Default is dot. "
                "Available shapes: box, crow, curve, icurve, diamond, dot, inv, "
                "none, normal, tee, vee.",
            },
            "--color-code-deletions": {
                "action": "store_true",
                "default": False,
                "dest": "color_code_deletions",
                "help": "Color the relations according to their on_delete setting, "
                "where it is applicable. The colors are: red (CASCADE), "
                "orange (SET_NULL), green (SET_DEFAULT), yellow (SET), "
                "blue (PROTECT), grey (DO_NOTHING), and purple (RESTRICT).",
            },
            "--rankdir": {
                "action": "store",
                "default": "TB",
                "dest": "rankdir",
                "choices": ["TB", "BT", "LR", "RL"],
                "help": "Set direction of graph layout. Supported directions: "
                "TB, LR, BT and RL. Corresponding to directed graphs drawn from "
                "top to bottom, from left to right, from bottom to top, and from "
                "right to left, respectively. Default is TB.",
            },
            "--ordering": {
                "action": "store",
                "default": None,
                "dest": "ordering",
                "choices": ["in", "out"],
                "help": "Controls how the edges are arranged. Supported orderings: "
                '"in" (incoming relations first), "out" (outgoing relations first). '
                "Default is None.",
            },
        }

        defaults = getattr(settings, "GRAPH_MODELS", None)

        if defaults:
            for argument in self.arguments:
                arg_split = argument.split(" ")
                setting_opt = arg_split[0].lstrip("-").replace("-", "_")
                if setting_opt in defaults:
                    self.arguments[argument]["default"] = defaults[setting_opt]

        super().__init__(*args, **kwargs)

    def add_arguments(self, parser):
        """Unpack self.arguments for parser.add_arguments."""
        parser.add_argument("app_label", nargs="*")
        for argument in self.arguments:
            parser.add_argument(*argument.split(" "), **self.arguments[argument])

    @signalcommand
    def handle(self, *args, **options):
        args = options["app_label"]
        if not args and not options["all_applications"]:
            default_app_labels = getattr(settings, "GRAPH_MODELS", {}).get("app_labels")
            if default_app_labels:
                args = default_app_labels
            else:
                raise CommandError("need one or more arguments for appname")

        # Determine output format based on options, file extension, and library
        # availability.
        outputfile = options.get("outputfile") or ""
        _, outputfile_ext = os.path.splitext(outputfile)
        outputfile_ext = outputfile_ext.lower()
        output_opts_names = ["pydot", "pygraphviz", "json", "dot"]
        output_opts = {k: v for k, v in options.items() if k in output_opts_names}
        output_opts_count = sum(output_opts.values())
        if output_opts_count > 1:
            raise CommandError(
                "Only one of %s can be set."
                % ", ".join(["--%s" % opt for opt in output_opts_names])
            )

        if output_opts_count == 1:
            output = next(key for key, val in output_opts.items() if val)
        elif not outputfile:
            # When neither outputfile nor a output format option are set,
            # default to printing .dot format to stdout. Kept for backward
            # compatibility.
            output = "dot"
        elif outputfile_ext == ".dot":
            output = "dot"
        elif outputfile_ext == ".json":
            output = "json"
        elif HAS_PYGRAPHVIZ:
            output = "pygraphviz"
        elif HAS_PYDOT:
            output = "pydot"
        else:
            raise CommandError(
                "Neither pygraphviz nor pydotplus could be found to generate the image."
                " To generate text output, use the --json or --dot options."
            )

        if options.get("rankdir") != "TB" and output not in [
            "pydot",
            "pygraphviz",
            "dot",
        ]:
            raise CommandError(
                "--rankdir is not supported for the chosen output format"
            )

        if options.get("ordering") and output not in ["pydot", "pygraphviz", "dot"]:
            raise CommandError(
                "--ordering is not supported for the chosen output format"
            )

        # Consistency check: Abort if --pygraphviz or --pydot options are set
        # but no outputfile is specified. Before 2.1.4 this silently fell back
        # to printind .dot format to stdout.
        if output in ["pydot", "pygraphviz"] and not outputfile:
            raise CommandError(
                "An output file (--output) must be specified when --pydot or "
                "--pygraphviz are set."
            )

        cli_options = " ".join(sys.argv[2:])
        graph_models = ModelGraph(args, cli_options=cli_options, **options)
        graph_models.generate_graph_data()

        if output == "json":
            graph_data = graph_models.get_graph_data(as_json=True)
            return self.render_output_json(graph_data, outputfile)

        graph_data = graph_models.get_graph_data(as_json=False)

        theme = options["theme"]
        template_name = os.path.join(
            "django_extensions", "graph_models", theme, "digraph.dot"
        )
        template = loader.get_template(template_name)

        graph_data = retheme(graph_data, app_style=options["app-style"])
        dotdata = generate_dot(graph_data, template=template)

        if output == "pygraphviz":
            return self.render_output_pygraphviz(dotdata, **options)
        if output == "pydot":
            return self.render_output_pydot(dotdata, **options)
        self.print_output(dotdata, outputfile)

    def print_output(self, dotdata, output_file=None):
        """Write model data to file or stdout in DOT (text) format."""
        if isinstance(dotdata, bytes):
            dotdata = dotdata.decode()

        if output_file:
            with open(output_file, "wt") as dot_output_f:
                dot_output_f.write(dotdata)
        else:
            self.stdout.write(dotdata)

    def render_output_json(self, graph_data, output_file=None):
        """Write model data to file or stdout in JSON format."""
        if output_file:
            with open(output_file, "wt") as json_output_f:
                json.dump(graph_data, json_output_f)
        else:
            self.stdout.write(json.dumps(graph_data))

    def render_output_pygraphviz(self, dotdata, **kwargs):
        """Render model data as image using pygraphviz."""
        if not HAS_PYGRAPHVIZ:
            raise CommandError("You need to install pygraphviz python module")

        version = pygraphviz.__version__.rstrip("-svn")
        try:
            if tuple(int(v) for v in version.split(".")) < (0, 36):
                # HACK around old/broken AGraph before version 0.36
                #   (ubuntu ships with this old version)
                tmpfile = tempfile.NamedTemporaryFile()
                tmpfile.write(dotdata)
                tmpfile.seek(0)
                dotdata = tmpfile.name
        except ValueError:
            pass

        graph = pygraphviz.AGraph(dotdata)
        graph.layout(prog=kwargs["layout"])
        graph.draw(kwargs["outputfile"])

    def render_output_pydot(self, dotdata, **kwargs):
        """Render model data as image using pydot."""
        if not HAS_PYDOT:
            raise CommandError("You need to install pydot python module")

        graph = pydot.graph_from_dot_data(dotdata)
        if not graph:
            raise CommandError("pydot returned an error")
        if isinstance(graph, (list, tuple)):
            if len(graph) > 1:
                sys.stderr.write(
                    "Found more then one graph, rendering only the first one.\n"
                )
            graph = graph[0]

        output_file = kwargs["outputfile"]
        formats = [
            "bmp",
            "canon",
            "cmap",
            "cmapx",
            "cmapx_np",
            "dot",
            "dia",
            "emf",
            "em",
            "fplus",
            "eps",
            "fig",
            "gd",
            "gd2",
            "gif",
            "gv",
            "imap",
            "imap_np",
            "ismap",
            "jpe",
            "jpeg",
            "jpg",
            "metafile",
            "pdf",
            "pic",
            "plain",
            "plain-ext",
            "png",
            "pov",
            "ps",
            "ps2",
            "svg",
            "svgz",
            "tif",
            "tiff",
            "tk",
            "vml",
            "vmlz",
            "vrml",
            "wbmp",
            "webp",
            "xdot",
        ]
        ext = output_file[output_file.rfind(".") + 1 :]
        format_ = ext if ext in formats else "raw"
        graph.write(output_file, format=format_)