_parse_xml_element()   F
last analyzed

Complexity

Conditions 10

Size

Total Lines 31

Duplication

Lines 13
Ratio 41.94 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 13
loc 31
rs 3.1304
cc 10

How to fix   Complexity   

Complexity

Complex classes like _parse_xml_element() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
#################################################################
2
# MET v2 Metadate Explorer Tool
3
#
4
# This Software is Open Source. See License: https://github.com/TERENA/met/blob/master/LICENSE.md
5
# Copyright (c) 2012, TERENA All rights reserved.
6
#
7
# This Software is based on MET v1 developed for TERENA by Yaco Sistemas, http://www.yaco.es/
8
# MET v2 was developed for TERENA by Tamim Ziai, DAASI International GmbH, http://www.daasi.de
9
# Current version of MET has been revised for performance improvements by Andrea Biancini,
10
# Consortium GARR, http://www.garr.it
11
##########################################################################
12
13
import csv
14
from xml.dom.minidom import Document
15
16
from django.http import HttpResponse, HttpResponseBadRequest
17
from django.template.defaultfilters import slugify
18
import simplejson as json
19
20
21
# Taken from http://djangosnippets.org/snippets/790/
22
def export_csv(model, filename, fields):
23
    response = HttpResponse(content_type='text/csv')
24
    response['Content-Disposition'] = ('attachment; filename=%s.csv'
25
                                       % slugify(filename))
26
    writer = csv.writer(response)
27
    # Write headers to CSV file
28
29
    writer.writerow(fields)
30
31
    # Write data to CSV file
32
    for obj in model:
33
        row = []
34
        for field in fields:
35
            row.append("%s" % obj[field])
36
        writer.writerow(row)
37
    # Return CSV file to browser as download
38
    return response
39
40
41
def export_json(model, filename, fields):
42
    objs = []
43
44
    for obj in model:
45
        item = {}
46
        for field in fields:
47
            if type(obj[field]) == set:
48
                item[field] = list(obj[field])
49
            else:
50
                item[field] = obj[field]
51
52
        objs.append(item)
53
    # Return JS file to browser as download
54
    serialized = json.dumps(objs)
55
    response = HttpResponse(serialized, content_type='application/json')
56
    response['Content-Disposition'] = ('attachment; filename=%s.json'
57
                                       % slugify(filename))
58
    return response
59
60
61
def _parse_xml_element(xml, father, structure):
62
    if type(structure) == dict:
63
        for k in structure:
64
            tag = xml.createElement(k)
65
            father.appendChild(tag)
66
            _parse_xml_element(xml, tag, structure[k])
67
    elif type(structure) == tuple:
68
        tag_name = father.tagName
69
        for l in list(structure):
70
            tag = xml.createElement(tag_name)
71
            _parse_xml_element(xml, tag, l)
72
            father.appendChild(tag)
73
    elif type(structure) == list:
74
        tag_name = father.tagName
75
        for l in structure:
76
            tag = xml.createElement(tag_name)
77
            _parse_xml_element(xml, tag, l)
78
            father.appendChild(tag)
79 View Code Duplication
    elif type(structure) == set:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
80
        tag_name = father.tagName
81
        for l in list(structure):
82
            tag = xml.createElement(tag_name)
83
            _parse_xml_element(xml, tag, l)
84
            father.appendChild(tag)
85
    else:
86
        if type(structure) == unicode:
87
            data = structure.encode("ascii", errors="xmlcharrefreplace")
88
        else:
89
            data = str(structure)
90
        tag = xml.createTextNode(data)
91
        father.appendChild(tag)
92
93
94
def export_xml(model, filename, fields=None):
95
    xml = Document()
96
    root = xml.createElement(filename)
97
    for obj in model:
98
        elem = xml.createElement("entity")
99
        _parse_xml_element(xml, elem, obj)
100
        root.appendChild(elem)
101
    xml.appendChild(root)
102
103
    # Return xml file to browser as download
104
    response = HttpResponse(xml.toxml(), content_type='application/xml')
105
    response['Content-Disposition'] = ('attachment; filename=%s.xml'
106
                                       % slugify(filename))
107
    return response
108
109
110
export_modes = {
111
    'csv': export_csv,
112
    'json': export_json,
113
    'xml': export_xml,
114
}
115
116
117
def export_query_set(mode, qs, filename, fields=None):
118
    if mode in export_modes:
119
        return export_modes[mode](qs, filename, fields)
120
    else:
121
        content = "Error 400, Format %s is not supported" % mode
122
        return HttpResponseBadRequest(content)
123