1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
10 from functools import wraps
13 from inspect import getargspec
15 from django.core.mail import send_mail
16 from django.http import HttpResponse
17 from django.template import RequestContext
18 from django.template.loader import render_to_string
19 from django.utils import timezone
20 from django.conf import settings
21 from django.utils.translation import ugettext
23 tz = pytz.timezone(settings.TIME_ZONE)
26 def localtime_to_utc(localtime):
27 return timezone.utc.normalize(
28 tz.localize(localtime)
33 return dt.strftime('%Y/%m/%d %H:%M:%S UTC')
37 if not os.path.isdir(path):
41 def stringify_keys(dictionary):
42 return dict((keyword.encode('ascii'), value)
43 for keyword, value in dictionary.iteritems())
46 def json_encode(obj, sort_keys=True, ensure_ascii=False):
47 return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
51 return json.loads(obj)
54 def json_decode_fallback(value):
56 return json_decode(value)
61 class AjaxError(Exception):
65 def ajax(login_required=False, method=None, template=None, permission_required=None):
68 def ajax_view(request):
72 request_params = request.POST
74 request_params = request.GET
75 fun_params, xx, fun_kwargs, defaults = getargspec(fun)
77 required_params = fun_params[1:-len(defaults)]
79 required_params = fun_params[1:]
80 missing_params = set(required_params) - set(request_params)
83 'result': 'missing params',
84 'missing': ', '.join(missing_params),
88 request_params = dict(
89 (key, json_decode_fallback(value))
90 for key, value in request_params.iteritems()
91 if fun_kwargs or key in fun_params)
92 kwargs.update(stringify_keys(request_params))
94 if login_required and not request.user.is_authenticated():
95 res = {'result': 'logout'}
96 if (permission_required and
97 not request.user.has_perm(permission_required)):
98 res = {'result': 'access denied'}
101 res = fun(request, **kwargs)
103 res = {'html': render_to_string(template, res, RequestContext(request))}
104 except AjaxError as e:
105 res = {'result': e.args[0]}
106 if 'result' not in res:
108 return HttpResponse(json_encode(res), content_type='application/json; charset=utf-8',
109 status=200 if res['result'] == 'ok' else 400)
116 def send_noreply_mail(subject, message, recipient_list, **kwargs):
118 u'[WolneLektury] ' + subject,
119 message + u"\n\n-- \n" + ugettext(u'Message sent automatically. Please do not reply.'),
120 'no-reply@wolnelektury.pl', recipient_list, **kwargs)
123 # source: https://docs.python.org/2/library/csv.html#examples
124 class UnicodeCSVWriter(object):
126 A CSV writer which will write rows to CSV file "f",
127 which is encoded in the given encoding.
130 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
131 # Redirect output to a queue
132 self.queue = cStringIO.StringIO()
133 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
135 self.encoder = codecs.getincrementalencoder(encoding)()
137 def writerow(self, row):
138 self.writer.writerow([s.encode("utf-8") for s in row])
139 # Fetch UTF-8 output from the queue ...
140 data = self.queue.getvalue()
141 data = data.decode("utf-8")
142 # ... and reencode it into the target encoding
143 data = self.encoder.encode(data)
144 # write to the target stream
145 self.stream.write(data)
147 self.queue.truncate(0)
149 def writerows(self, rows):