thread-safe random
[edumed.git] / edumed / utils.py
1 # -*- coding: utf-8 -*-
2 import codecs
3 import csv
4 import cStringIO
5
6 from settings.apps import INSTALLED_APPS
7
8
9 # source: https://docs.python.org/2/library/csv.html#examples
10 class UnicodeCSVWriter(object):
11     """
12     A CSV writer which will write rows to CSV file "f",
13     which is encoded in the given encoding.
14     """
15
16     def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
17         # Redirect output to a queue
18         self.queue = cStringIO.StringIO()
19         self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
20         self.stream = f
21         self.encoder = codecs.getincrementalencoder(encoding)()
22
23     def writerow(self, row):
24         self.writer.writerow([s.encode("utf-8") for s in row])
25         # Fetch UTF-8 output from the queue ...
26         data = self.queue.getvalue()
27         data = data.decode("utf-8")
28         # ... and reencode it into the target encoding
29         data = self.encoder.encode(data)
30         # write to the target stream
31         self.stream.write(data)
32         # empty queue
33         self.queue.truncate(0)
34
35     def writerows(self, rows):
36         for row in rows:
37             self.writerow(row)
38
39
40 def process_app_deps(list_with_deps):
41     return tuple(
42         (x[0] if type(x) == tuple else x)
43         for x in list_with_deps
44         if type(x) != tuple or x[1] in INSTALLED_APPS)