gravatar.py 818 B

123456789101112131415161718192021222324252627282930313233
  1. from StringIO import StringIO
  2. from PIL import Image
  3. import requests
  4. from misago.conf import settings
  5. from misago.users.avatars import cache
  6. GRAVATAR_URL = 'http://www.gravatar.com/avatar/%s?s=%s&d=404'
  7. class GravatarError(RuntimeError):
  8. pass
  9. class NoGravatarAvailable(RuntimeError):
  10. pass
  11. def set_avatar(user):
  12. url_formats = (user.email_hash, max(settings.MISAGO_AVATARS_SIZES))
  13. try:
  14. r = requests.get(GRAVATAR_URL % url_formats, timeout=5)
  15. if r.status_code != 200:
  16. raise NoGravatarAvailable(
  17. 'gravatar is not available for this e-mail')
  18. image = Image.open(StringIO(r.content))
  19. cache.store_new_avatar(user, image)
  20. except requests.exceptions.RequestException:
  21. raise GravatarError('failed to connect to gravatar servers')