downloaded.py 900 B

123456789101112131415161718192021222324252627282930313233
  1. from io import BytesIO
  2. import requests
  3. from PIL import Image
  4. from . import store
  5. class AvatarDownloadError(RuntimeError):
  6. pass
  7. def set_avatar(user, avatar_url):
  8. try:
  9. r = requests.get(avatar_url, timeout=5)
  10. if r.status_code != 200:
  11. raise AvatarDownloadError("could not retrieve avatar from the server")
  12. image = Image.open(BytesIO(r.content))
  13. # Crop avatar into square
  14. width, height = image.size
  15. if width > height:
  16. left = int((width - height) / 2)
  17. image = image.crop((left, 0, width + left, height))
  18. elif height > width:
  19. top = int((height - width) / 2)
  20. image = image.crop((0, top, width, top + height))
  21. store.store_new_avatar(user, image)
  22. except requests.exceptions.RequestException:
  23. raise AvatarDownloadError("failed to connect to avatar server")