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

Dict2XML   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 37
Duplicated Lines 40.54 %

Importance

Changes 0
Metric Value
wmc 9
c 0
b 0
f 0
dl 15
loc 37
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 7 2
A __str__() 0 2 1
B build() 15 22 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
def _serialize_value_to_csv(value):
21
    if type(value) is list:
22
        vallist = [_serialize_value_to_csv(v) for v in value]
23
        serialized = ", ".join(vallist)
24
    elif type(value) is dict:
25
        vallist = [_serialize_value_to_csv(v) for v in value.values()]
26
        serialized = ", ".join(vallist)
27
    else:
28
        serialized = "%s" % value
29
30
    return serialized
31
32
def export_entity_csv(entity):
33
    response = HttpResponse(content_type='text/csv')
34
    response['Content-Disposition'] = ('attachment; filename=%s.csv'
35
                                       % slugify(entity))
36
    writer = csv.writer(response)
37
    edict = entity.to_dict()
38
39
    writer.writerow(edict.keys())
40
    # Write data to CSV file
41
    row = []
42
    for key, value in edict.items():
43
        row.append(_serialize_value_to_csv(value))
44
    row_ascii = [v.encode("ascii", "ignore") for v in row]
45
46
    writer.writerow(row_ascii)
47
    # Return CSV file to browser as download
48
    return response
49
50
51
def export_entity_json(entity):
52
    # Return JS file to browser as download
53
    serialized = json.dumps(entity.to_dict())
54
    response = HttpResponse(serialized, content_type='application/json')
55
    response['Content-Disposition'] = ('attachment; filename=%s.json'
56
                                       % slugify(entity))
57
    return response
58
59
60
class Dict2XML(object):
61
    """ http://stackoverflow.com/questions/1019895/serialize-python-dictionary-to-xml """
62
    doc = Document()
63
64
    def __init__(self, structure):
65
        if len(structure) == 1:
66
            root_name = str(structure.keys()[0])
67
            self.root = self.doc.createElement(root_name)
68
69
            self.doc.appendChild(self.root)
70
            self.build(self.root, structure[root_name])
71
72
    def build(self, father, structure):
73
        if type(structure) == dict:
74
            for k in structure:
75
                tag = self.doc.createElement(k)
76
                father.appendChild(tag)
77
                self.build(tag, structure[k])
78
79 View Code Duplication
        elif type(structure) == list:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
80
            grand_father = father.parentNode
81
            tag_name = father.tag_name
82
            grand_father.removeChild(father)
83
            for l in structure:
84
                tag = self.doc.createElement(tag_name)
85
                self.build(tag, l)
86
                grand_father.appendChild(tag)
87
        else:
88
            if type(structure) == unicode:
89
                data = structure.encode("ascii", errors="xmlcharrefreplace")
90
            else:
91
                data = str(structure)
92
            tag = self.doc.createTextNode(data)
93
            father.appendChild(tag)
94
95
    def __str__(self):
96
        return self.doc.toprettyxml(indent=" ")
97
98
99
def export_entity_xml(entity):
100
    entity_xml = Dict2XML({"Entity": entity.to_dict()})
101
102
    # Return XML file to browser as download
103
    response = HttpResponse(str(entity_xml), content_type='application/xml')
104
    response['Content-Disposition'] = ('attachment; filename=%s.xml'
105
                                       % slugify(entity))
106
    return response
107
108
109
export_entity_modes = {
110
            'csv': export_entity_csv,
111
            'json': export_entity_json,
112
            'xml': export_entity_xml,
113
        }
114
115
116
def export_entity(mode, entity):
117
    if mode in export_entity_modes:
118
        return export_entity_modes[mode](entity)
119
    else:
120
        content = "Error 400, Format %s is not supported" % mode
121
        return HttpResponseBadRequest(content)
122