gravatar.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
  2. # Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
  3. # Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
  4. # Copyright (C) 2014 Anler Hernández <hello@anler.me>
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. import hashlib
  18. import copy
  19. from urllib.parse import urlencode
  20. from django.conf import settings
  21. from django.templatetags.static import static
  22. GRAVATAR_BASE_URL = "//www.gravatar.com/avatar/{}?{}"
  23. def get_gravatar_url(email: str, **options) -> str:
  24. """Get the gravatar url associated to an email.
  25. :param options: Additional options to gravatar.
  26. - `default` defines what image url to show if no gravatar exists
  27. - `size` defines the size of the avatar.
  28. :return: Gravatar url.
  29. """
  30. params = copy.copy(options)
  31. default_avatar = getattr(settings, "GRAVATAR_DEFAULT_AVATAR", None)
  32. default_size = getattr(settings, "GRAVATAR_AVATAR_SIZE", None)
  33. avatar = options.get("default", None)
  34. size = options.get("size", None)
  35. if avatar:
  36. params["default"] = avatar
  37. elif default_avatar:
  38. params["default"] = static(default_avatar)
  39. if size:
  40. params["size"] = size
  41. elif default_size:
  42. params["size"] = default_size
  43. email_hash = hashlib.md5(email.lower().encode()).hexdigest()
  44. url = GRAVATAR_BASE_URL.format(email_hash, urlencode(params))
  45. return url