Coverage for ivatar/ivataraccount/gravatar.py: 94%

18 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-05-12 23:12 +0000

1# -*- coding: utf-8 -*- 

2""" 

3Helper method to fetch Gravatar image 

4""" 

5from ssl import SSLError 

6from urllib.request import HTTPError, URLError 

7from ivatar.utils import urlopen 

8import hashlib 

9 

10from ..settings import AVATAR_MAX_SIZE 

11 

12 

13def get_photo(email): 

14 """ 

15 Fetch photo from Gravatar, given an email address 

16 """ 

17 hash_object = hashlib.new("md5") 

18 hash_object.update(email.lower().encode("utf-8")) 

19 thumbnail_url = ( 

20 "https://secure.gravatar.com/avatar/" 

21 + hash_object.hexdigest() 

22 + "?s=%i&d=404" % AVATAR_MAX_SIZE 

23 ) 

24 image_url = ( 

25 f"https://secure.gravatar.com/avatar/{hash_object.hexdigest()}?s=512&d=404" 

26 ) 

27 

28 # Will redirect to the public profile URL if it exists 

29 service_url = f"http://www.gravatar.com/{hash_object.hexdigest()}" 

30 

31 try: 

32 urlopen(image_url) 

33 except HTTPError as exc: 

34 if exc.code not in [404, 503]: 

35 print(f"Gravatar fetch failed with an unexpected {exc.code} HTTP error") 

36 return False 

37 except URLError as exc: # pragma: no cover 

38 print(f"Gravatar fetch failed with URL error: {exc.reason}") 

39 return False # pragma: no cover 

40 except SSLError as exc: # pragma: no cover 

41 print(f"Gravatar fetch failed with SSL error: {exc.reason}") 

42 return False # pragma: no cover 

43 

44 return { 

45 "thumbnail_url": thumbnail_url, 

46 "image_url": image_url, 

47 "width": AVATAR_MAX_SIZE, 

48 "height": AVATAR_MAX_SIZE, 

49 "service_url": service_url, 

50 "service_name": "Gravatar", 

51 }