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