Python Flask - Gravatar Issue

492 views Asked by At

Using Flask - I've got the coding to get the gravatar image URL and I've printed it in the console to see if it's working and it is. I've got the hashlib md5 bit being put into a variable called Avatar.

And in my html file I have this to display the avatar

<img src="{{ avatar }}">

But nothing is displayed.

When I use inspect element, all that is in that part is this

<img src="">
1

There are 1 answers

0
Gitau Harrison On

Since every user in an application may need an avatar, it is ideal to update the User model with a gravatar image/identicon. You can do this in models.py, as follows:

from hashlib import md5

class User(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(64), index = True, unique = True)
    email = db.Column(db.String(120), index =  True, unique = True)
    password_hash = db.Column(db.String(128))

    def gravatar(self, size):
        digest = md5(self.email.lower().encode('utf-8')).hextdigest()
        return 'https://www.gravatar.com/avatar/{}?d=identicon&s={}'.format(digest, size)

In your <>.html file, you can add the dynamic component as follows:

<img scr="{{ user.avatar(<choose a size>) }">

This should display an identicon image on your HTML file without the need to define avatar = avatar when rendering the HTML template.