Completed
Push — master ( 28b0ba...17cdbf )
by Andrea
01:44
created

_parse_xml_element()   F

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
import hashlib
16
17
from django.http import HttpResponse, HttpResponseBadRequest
18
from django.template.defaultfilters import slugify
19
import simplejson as json
20
21
22
## Taken from http://djangosnippets.org/snippets/790/
23
def export_csv(model, filename, fields):
24
    response = HttpResponse(content_type='text/csv')
25
    response['Content-Disposition'] = ('attachment; filename=%s.csv'
26
                                       % slugify(filename))
27
    writer = csv.writer(response)
28
    # Write headers to CSV file
29
30
    writer.writerow(fields)
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
    for obj in model:
44
        item = {}
45
        for field in fields:
46
            if type(obj[field]) == set:
47
                item[field] = list(obj[field])
48
            else:
49
                item[field] = obj[field]
50
51
        objs.append(item)
52
    # Return JS file to browser as download
53
    serialized = json.dumps(objs)
54
    response = HttpResponse(serialized, content_type='application/json')
55
    response['Content-Disposition'] = ('attachment; filename=%s.json'
56
                                       % slugify(filename))
57
    return response
58
59
60
def _parse_xml_element(xml, father, structure):
61
    if type(structure) == dict:
62
        for k in structure:
63
            tag = xml.createElement(k)
64
            father.appendChild(tag)
65
            _parse_xml_element(xml, tag, structure[k])
66
    elif type(structure) == tuple:
67
        tag_name = father.tagName
68
        for l in list(structure):
69
            tag = xml.createElement(tag_name)
70
            _parse_xml_element(xml, tag, l)
71
            father.appendChild(tag)
72
    elif type(structure) == list:
73
        tag_name = father.tagName
74
        for l in structure:
75
            tag = xml.createElement(tag_name)
76
            _parse_xml_element(xml, tag, l)
77
            father.appendChild(tag)
78 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...
79
        tag_name = father.tagName
80
        for l in list(structure):
81
            tag = xml.createElement(tag_name)
82
            _parse_xml_element(xml, tag, l)
83
            father.appendChild(tag)
84
    else:
85
        if type(structure) == unicode:
86
            data = structure.encode("ascii", errors="xmlcharrefreplace")
87
        else:
88
            data = str(structure)
89
        tag = xml.createTextNode(data)
90
        father.appendChild(tag)
91
92
93
def export_xml(model, filename, fields):
94
    xml = Document()
95
    root = xml.createElement(filename)
96
    xml.appendChild(root)
97
    for obj in model:
98
        _parse_xml_element(xml, root, obj)
99
    # Return xml file to browser as download
100
    response = HttpResponse(xml.toxml(), content_type='application/xml')
101
    response['Content-Disposition'] = ('attachment; filename=%s.xml'
102
                                       % slugify(filename))
103
    return response
104
105
106
export_modes = {
107
            'csv': export_csv,
108
            'json': export_json,
109
            'xml': export_xml,
110
        }
111
112
113
def export_query_set(mode, qs, filename, fields=None):
114
    if mode in export_modes:
115
        return export_modes[mode](qs, filename, fields)
116
    else:
117
        content = "Error 400, Format %s is not supported" % mode
118
        return HttpResponseBadRequest(content)
119