Coverage for ivatar/ivataraccount/gravatar.py: 100%
17 statements
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-26 00:11 +0000
« prev ^ index » next coverage.py v7.6.9, created at 2024-12-26 00:11 +0000
1# -*- coding: utf-8 -*-
2"""
3Helper method to fetch Gravatar image
4"""
5from ssl import SSLError
6from urllib.request import urlopen, HTTPError, URLError
7import hashlib
9from ..settings import AVATAR_MAX_SIZE
11URL_TIMEOUT = 5 # in seconds
14def get_photo(email):
15 """
16 Fetch photo from Gravatar, given an email address
17 """
18 hash_object = hashlib.new("md5")
19 hash_object.update(email.lower().encode("utf-8"))
20 thumbnail_url = (
21 "https://secure.gravatar.com/avatar/"
22 + hash_object.hexdigest()
23 + "?s=%i&d=404" % AVATAR_MAX_SIZE
24 )
25 image_url = (
26 "https://secure.gravatar.com/avatar/" + hash_object.hexdigest() + "?s=512&d=404"
27 )
29 # Will redirect to the public profile URL if it exists
30 service_url = "http://www.gravatar.com/" + hash_object.hexdigest()
32 try:
33 urlopen(image_url, timeout=URL_TIMEOUT)
34 except HTTPError as exc:
35 if exc.code != 404 and exc.code != 503:
36 print( # pragma: no cover
37 "Gravatar fetch failed with an unexpected %s HTTP error" % exc.code
38 )
39 return False
40 except URLError as exc: # pragma: no cover
41 print(
42 "Gravatar fetch failed with URL error: %s" % exc.reason
43 ) # pragma: no cover
44 return False # pragma: no cover
45 except SSLError as exc: # pragma: no cover
46 print(
47 "Gravatar fetch failed with SSL error: %s" % exc.reason
48 ) # pragma: no cover
49 return False # pragma: no cover
51 return {
52 "thumbnail_url": thumbnail_url,
53 "image_url": image_url,
54 "width": AVATAR_MAX_SIZE,
55 "height": AVATAR_MAX_SIZE,
56 "service_url": service_url,
57 "service_name": "Gravatar",
58 }