1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. 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
25 return dt.strftime('%Y/%m/%d %H:%M:%S UTC')
29 if not os.path.isdir(path):
33 def stringify_keys(dictionary):
34 return dict((keyword.encode('ascii'), value)
35 for keyword, value in dictionary.items())
38 def json_encode(obj, sort_keys=True, ensure_ascii=False):
39 return json.dumps(obj, sort_keys=sort_keys, ensure_ascii=ensure_ascii)
43 return json.loads(obj)
46 def json_decode_fallback(value):
48 return json_decode(value)
53 class AjaxError(Exception):
57 def ajax(login_required=False, method=None, template=None, permission_required=None):
60 def ajax_view(request):
64 request_params = request.POST
66 request_params = request.GET
67 fun_params, xx, fun_kwargs, defaults = getargspec(fun)
69 required_params = fun_params[1:-len(defaults)]
71 required_params = fun_params[1:]
72 missing_params = set(required_params) - set(request_params)
75 'result': 'missing params',
76 'missing': ', '.join(missing_params),
80 request_params = dict(
81 (key, json_decode_fallback(value))
82 for key, value in request_params.items()
83 if fun_kwargs or key in fun_params)
84 kwargs.update(stringify_keys(request_params))
86 if login_required and not request.user.is_authenticated:
87 res = {'result': 'logout'}
88 if (permission_required and
89 not request.user.has_perm(permission_required)):
90 res = {'result': 'access denied'}
93 res = fun(request, **kwargs)
95 res = {'html': render_to_string(template, res, request=request)}
96 except AjaxError as e:
97 res = {'result': e.args[0]}
98 if 'result' not in res:
100 return HttpResponse(json_encode(res), content_type='application/json; charset=utf-8',
101 status=200 if res['result'] == 'ok' else 400)
108 def send_noreply_mail(subject, message, recipient_list, **kwargs):
110 '[WolneLektury] ' + subject,
111 message + "\n\n-- \nWiadomość wysłana automatycznie. Prosimy nie odpowiadać.",
112 'no-reply@wolnelektury.pl', recipient_list, **kwargs)
115 # source: https://docs.python.org/2/library/csv.html#examples
116 class UnicodeCSVWriter(object):
118 A CSV writer which will write rows to CSV file "f",
119 which is encoded in the given encoding.
122 def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
123 # Redirect output to a queue
124 self.queue = BytesIO()
125 self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
127 self.encoder = codecs.getincrementalencoder(encoding)()
129 def writerow(self, row):
130 self.writer.writerow([s.encode("utf-8") for s in row])
131 # Fetch UTF-8 output from the queue ...
132 data = self.queue.getvalue()
133 data = data.decode("utf-8")
134 # ... and reencode it into the target encoding
135 data = self.encoder.encode(data)
136 # write to the target stream
137 self.stream.write(data)
139 self.queue.truncate(0)
141 def writerows(self, rows):
146 # the original re.escape messes with unicode
148 return re.sub(r"[(){}\[\].*?|^$\\+-]", r"\\\g<0>", s)
151 def get_cached_render_key(instance, property_name, language=None):
153 language = get_language()
154 return 'cached_render:%s.%s:%s:%s' % (
155 type(instance).__name__,
162 def cached_render(template_name, timeout=24 * 60 * 60):
163 def decorator(method):
166 key = get_cached_render_key(self, method.__name__)
167 content = cache.get(key)
169 context = method(self)
170 content = render_to_string(template_name, context)
171 cache.set(key, str(content), timeout=timeout)
173 content = mark_safe(content)
179 def clear_cached_renders(bound_method):
180 for lc, ln in settings.LANGUAGES:
182 get_cached_render_key(
183 bound_method.__self__,
184 bound_method.__name__,
190 class YesNoFilter(admin.SimpleListFilter):
191 def lookups(self, request, model_admin):
197 def queryset(self, request, queryset):
198 if self.value() == 'yes':
199 return queryset.filter(self.q)
200 elif self.value() == 'no':
201 return queryset.exclude(self.q)
204 def is_ajax(request):
205 return request.headers.get('x-requested-with') == 'XMLHttpRequest'