Search code examples
pythongoogle-plusgoogle-signinpython-social-auth

Python Social Auth get Google avatar


Is there a way to get the Google profile picture url using python social auth?

So, this is what I do for facebook and twitter, add a pipeline with this code:

    if strategy.backend.name == 'facebook':
        url = 'http://graph.facebook.com/{0}/picture'.format(response['id'])

    elif strategy.backend.name == "twitter":
        if response['profile_image_url'] != '':
            url = response['profile_image_url']

    elif strategy.backend.name == "GoogleOAuth2":  # doesn't work
        user_id = response['id']
        url = "???"

First, I don't know what is the name of the backend, is it "GoogleOAuth2"? Second, what is the url I should use to save the profile's avatar?. Is this the way?


Solution

  • from social.backends.google import GoogleOAuth2
    
    def save_profile(backend, user, response, *args, **kwargs):
        if isinstance(backend, GoogleOAuth2):
            if response.get('image') and response['image'].get('url'):
                url = response['image'].get('url')
                ext = url.split('.')[-1]
                user.avatar.save(
                   '{0}.{1}'.format('avatar', ext),
                   ContentFile(urllib2.urlopen(url).read()),
                   save=False
                )
                user.save()