34d54464197d3c37dbe6089395b51fa32b0c9058
[django-libravatar.git] / django_libravatar / templatetags / libravatar_tags.py
1 # -*- coding: utf-8 -*-
2 # This file is part of django-libravatar, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from django.core.cache import cache
6 from django import template
7 from libravatar import libravatar_url
8 from django_libravatar.settings import LIBRAVATAR_DEFAULT, LIBRAVATAR_DEFAULT_HTTPS
9
10 register = template.Library()
11
12 @register.simple_tag(takes_context=True)
13 def libravatar(context, email, size=None):
14     https = context['request'].is_secure()
15     default = LIBRAVATAR_DEFAULT_HTTPS if https else LIBRAVATAR_DEFAULT_HTTP
16     if hasattr(default, '__call__'):
17         default = default(size)
18     if not email:
19         return default
20     cache_key = "%s:%d:%d" % (email, size, https)
21     print cache_key
22     url = cache.get(cache_key)
23     if url is None:
24         print 'fetching...'
25         url = libravatar_url(email,
26             https=https,
27             default=default,
28             size=size)
29         cache.set(cache_key, url, 60 * 60)
30     return url