1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from functools import wraps
7 from inspect import getargspec
13 from django.conf import settings
14 from django.contrib import admin
15 from django.core.cache import cache
16 from django.core.mail import send_mail
17 from django.http import HttpResponse
18 from django.template.loader import render_to_string
19 from django.utils.translation import get_language
20 from django.conf import settings
21 from django.utils.safestring import mark_safe
22 from django.utils.translation import gettext as _
26 return dt.strftime('%Y/%m/%d %H:%M:%S UTC')
30 if not os.path.isdir(path):
34 def stringify_keys(dictionary):
35 return dict((keyword.encode('ascii'), value)
36 for keyword, value in dictionary.items())
39 def json_encode(obj, sort_keys=True, ensure_ascii=False):
40 return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
44 return json.loads(obj)
47 def json_decode_fallback(value):
49 return json_decode(value)
54 class AjaxError(Exception):
58 def ajax(login_required=False, method=None, template=None, permission_required=None):
61 def ajax_view(request):
65 request_params = request.POST
67 request_params = request.GET
68 fun_params, xx, fun_kwargs, defaults = getargspec(fun)
70 required_params = fun_params[1:-len(defaults)]
72 required_params = fun_params[1:]
73 missing_params = set(required_params) - set(request_params)
76 'result': 'missing params',
77 'missing': ', '.join(missing_params),
81 request_params = dict(
82 (key, json_decode_fallback(value))
83 for key, value in request_params.items()
84 if fun_kwargs or key in fun_params)
85 kwargs.update(stringify_keys(request_params))
87 if login_required and not request.user.is_authenticated:
88 res = {'result': 'logout'}
89 if (permission_required and
90 not request.user.has_perm(permission_required)):
91 res = {'result': 'access denied'}
94 res = fun(request, **kwargs)
96 res = {'html': render_to_string(template, res, request=request)}
97 except AjaxError as e:
98 res = {'result': e.args[0]}
99 if 'result' not in res:
101 return HttpResponse(json_encode(res), content_type='application/json; charset=utf-8',
102 status=200 if res['result'] == 'ok' else 400)
109 def send_noreply_mail(subject, message, recipient_list, **kwargs):
111 '[WolneLektury] ' + subject,
112 message + "\n\n-- \n" + _('Message sent automatically. Please do not reply.'),
113 'no-reply@wolnelektury.pl', recipient_list, **kwargs)
116 # source: https://docs.python.org/2/library/csv.html#examples
117 class UnicodeCSVWriter(object):
119 A CSV writer which will write rows to CSV file "f",
120 which is encoded in the given encoding.
123 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
124 # Redirect output to a queue
125 self.queue = BytesIO()
126 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
128 self.encoder = codecs.getincrementalencoder(encoding)()
130 def writerow(self, row):
131 self.writer.writerow([s.encode("utf-8") for s in row])
132 # Fetch UTF-8 output from the queue ...
133 data = self.queue.getvalue()
134 data = data.decode("utf-8")
135 # ... and reencode it into the target encoding
136 data = self.encoder.encode(data)
137 # write to the target stream
138 self.stream.write(data)
140 self.queue.truncate(0)
142 def writerows(self, rows):
147 # the original re.escape messes with unicode
149 return re.sub(r"[(){}\[\].*?|^$\\+-]", r"\\\g<0>", s)
152 def get_cached_render_key(instance, property_name, language=None):
154 language = get_language()
155 return 'cached_render:%s.%s:%s:%s' % (
156 type(instance).__name__,
163 def cached_render(template_name, timeout=24 * 60 * 60):
164 def decorator(method):
167 key = get_cached_render_key(self, method.__name__)
168 content = cache.get(key)
170 context = method(self)
171 content = render_to_string(template_name, context)
172 cache.set(key, str(content), timeout=timeout)
174 content = mark_safe(content)
180 def clear_cached_renders(bound_method):
181 for lc, ln in settings.LANGUAGES:
183 get_cached_render_key(
184 bound_method.__self__,
185 bound_method.__name__,
191 class YesNoFilter(admin.SimpleListFilter):
192 def lookups(self, request, model_admin):
198 def queryset(self, request, queryset):
199 if self.value() == 'yes':
200 return queryset.filter(self.q)
201 elif self.value() == 'no':
202 return queryset.exclude(self.q)
205 def is_ajax(request):
206 return request.headers.get('x-requested-with') == 'XMLHttpRequest'