Sunday, January 30, 2011

Facebook and Pinax Avatars

Pinax is bundled with an app for managing avatars. If your users are uploading their photos, then using the avatar app is pretty straight forward. If you are grabbing a avatar from a users Facebook site, then things are not as easy.

The photo can be accessed using:

file = urllib.urlopen("https://graph.facebook.com/%s/picture?type=normal"%(user['id'],))

The problem comes when you try to save the photo to an avatar using something like this:

avatar=Avatar(user=request.user)
new_file = avatar.avatar.save(path, file.read())
avatar.save()

I was able to get it to work by saving it to a temp file, then wrapping it in a django File:

from tempfile import NamedTemporaryFile
from django.core.files import File
from avatar.models import Avatar,avatar_file_path

file = urllib.urlopen("https://graph.facebook.com/%s/picture?type=normal"%(user['id'],)) fp=NamedTemporaryFile(delete=True)
fp.write(file.read())
avatar=Avatar(user=request.user)
path = avatar_file_path(user=request.user,filename='facebook_%s.jpg'%date.today())
avatar.avatar.save(os.path.join(settings.MEDIA_ROOT,path),File(fp))
avatar.save()
fp.close()

I tried using StringIO, but could not get it to work.

No comments:

Post a Comment