Each time my user signs in, we pull his profile picture from Facebook. This means when he signs in, I need to check if the existing image is the same thing as the new image. Then, if it isn’t, I need to overwrite the existing image. I can probably hack this together, but what’s the optimal way to do this?
Here’s my model:
class UserProfile(models.Model):
avatar = models.ImageField(upload_to='img/users')
@receiver(pre_update, sender=FacebookBackend)
def update_user_profile(sender, user, response, details, **kwargs):
profile, created = UserProfile.objects.get_or_create(user=user)
if "id" in response:
from urllib2 import urlopen, HTTPError
from django.template.defaultfilters import slugify
from django.core.files.base import ContentFile
try:
url = "http://graph.facebook.com/%s/picture" \
% response["id"]
avatar = urlopen(url+'?type=large', timeout=15)
profile.avatar.save(slugify(user.id + 'a') + u'.jpg',
ContentFile(avatar.read()))
You can get the image from Facebook and the currently stored image, hash the data of both files and compare the hashes. That’s the common way to check whether images are the same. If the hashes are different then you can replace the currently stored image with the image from Facebook.
You can use
import hashlib; hashlib.sha1(data)(orhashlib.md5(data), this is not a security matter but purely for hashing purposes), wheredatacontains the contents of the image file.You could also check the filenames but that’s not reliable. It may be unlikely that a user will upload another profile image with the same filename, it’s still possible. If you are renaming the image files in your system then this approach isn’t possible either.