Installation de la version modifié de QBE dans src/
[auf_rh_dae.git] / src / qbe / django_qbe / exports.py
1 # -*- coding: utf-8 -*-
2 import codecs
3 import csv
4 from StringIO import StringIO
5
6 from django.http import HttpResponse
7 from django.utils.datastructures import SortedDict
8
9 __all__ = ("formats", )
10
11
12 class FormatsException(Exception):
13 pass
14
15
16 class Formats(SortedDict):
17
18 def add(self, format):
19 parent = self
20
21 def decorator(func):
22 if callable(func):
23 parent.update({format: func})
24 else:
25 raise FormatsException("func is not a function.")
26
27 return decorator
28
29
30 formats = Formats()
31
32
33 # Taken from http://docs.python.org/library/csv.html#csv-examples
34 class UnicodeWriter(object):
35 """
36 A CSV writer which will write rows to CSV file "f",
37 which is encoded in the given encoding.
38 """
39
40 def __init__(self, f, dialect=csv.excel_tab, encoding="utf-8", **kwds):
41 # Redirect output to a queue
42 self.queue = StringIO()
43 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
44 self.stream = f
45 self.encoder = codecs.getincrementalencoder(encoding)()
46
47 def writerow(self, row):
48 self.writer.writerow([unicode(s).encode("utf-8") for s in row])
49 # Fetch UTF-8 output from the queue ...
50 data = self.queue.getvalue()
51 data = data.decode("utf-8")
52 # ... and reencode it into the target encoding
53 data = self.encoder.encode(data)
54 # write to the target stream
55 self.stream.write(data)
56 # empty queue
57 self.queue.truncate(0)
58
59 def writerows(self, rows):
60 for row in rows:
61 self.writerow(row)
62
63
64 def base_export(labels, results):
65 output = StringIO()
66 w = UnicodeWriter(output)
67 w.writerow(labels)
68 for row in results:
69 w.writerow(row)
70 output.seek(0)
71 return output.read()
72
73
74 @formats.add("csv")
75 def csv_format(labels, results):
76 output = base_export(labels, results)
77 mimetype = "text/csv"
78 return HttpResponse(output, mimetype=mimetype)
79
80
81 @formats.add("ods")
82 def ods_format(labels, results):
83 output = base_export(labels, results)
84 mimetype = "application/vnd.oasis.opendocument.spreadsheet"
85 return HttpResponse(output, mimetype=mimetype)
86
87
88 @formats.add("xls")
89 def xls_format(labels, results):
90 output = base_export(labels, results)
91 mimetype = "application/vnd.ms-excel"
92 return HttpResponse(output, mimetype=mimetype)