Last Updated: February 25, 2016
·
1.357K
· bt3gl

Using Gravatar in an App (Python)

Gravatar associates avatar images with email addresses. Users create an
account at http://gravatar.com and then upload their images.

To generate the avatar URL for a given email address, its MD5 hash is calculated:

>>> import hashlib
>>> hashlib.md5('johnsmith@example.com'.encode('utf-8')).hexdigest()
'5f2f71a59bd9e62b0cc5fe4cd7216968'

The avatar URLs are then generated by appending the MD5 hash to URL http://
www.gravatar.com/avatar/ or https://secure.gravatar.com/avatar/.

For example, you can type http://www.gravatar.com/avatar/5f2f71a59bd9e62b0cc5fe4cd7216968 in your browser’s address bar to get the avatar image for the email address johnsmith@example.com , or a default generated image if that email address does not have an
avatar registered.

So, for example, in your Python application, you can have the following code:

def gravatar(self, size=100, default='identicon', rating='g'):
    if request.is_secure:
        url = 'https://secure.gravatar.com/avatar'
    else:
        url = 'http://www.gravatar.com/avatar'
    hash = hashlib.md5(self.email.encode('utf-8')).hexdigest()
    return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(url=url, hash=hash, size=size, default=default, rating=rating)