Source code for superdjango.contrib.accounts.avatars.utils

# Imports

from django.conf import settings
import hashlib
import os
from urllib.request import urlretrieve

# Exports

__all__ = (
    "get_gravatar_url",
)

# Functions


[docs]def get_gravatar_url(email, size=60): """Get the Gravatar URL for the given email address. :param email: The email address. :type email: str :param size: The desired size of the image. :type size: int :rtype: str """ # Get the hash used to identify the email. encoded_email = email.strip().lower().encode("utf-8") email_hash = hashlib.md5(encoded_email).hexdigest() # Check to see if the avatar has already been acquired. path = os.path.join(settings.MEDIA_ROOT, "avatars", "%s.jpg" % email_hash) if os.path.exists(path): return "%savatars/%s.jpg" % (settings.MEDIA_URL, email_hash) # Create the avatar directory as needed. base_path = os.path.dirname(path) if not os.path.exists(base_path): os.makedirs(base_path) # Get and save the image. url = "https://secure.gravatar.com/avatar/%s.jpg?s=%s" % (email_hash, size) urlretrieve(url, filename=path) # Return the local URL. # return "https://secure.gravatar.com/avatar/%s.jpg?s=%s" % (email_hash, size) return "%savatars/%s.jpg" % (settings.MEDIA_URL, email_hash)