5

有没有办法使用 python social auth 获取 Google 个人资料图片网址?

所以,这就是我为 facebook 和 twitter 做的,用这段代码添加一个管道:

    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 = "???"

首先,我不知道后端的名称是什么,是“GoogleOAuth2”吗?其次,我应该使用什么网址来保存个人资料的头像?。是这样吗?

4

4 回答 4

5
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()
于 2014-09-09T12:53:46.470 回答
2

要从社交登录中获取头像,您需要在您的应用程序中创建一个 pipeline.py 文件并将以下行添加到 settings.py:

SOCIAL_AUTH_PIPELINE = (

    'social.pipeline.social_auth.social_details',
    'social.pipeline.social_auth.social_uid',
    'social.pipeline.social_auth.auth_allowed',
    'social.pipeline.social_auth.social_user',
    'social.pipeline.user.get_username',
    'social.pipeline.user.create_user',
    'social.pipeline.social_auth.associate_user',
    'social.pipeline.social_auth.load_extra_data',
    'social.pipeline.user.user_details',
    'apps.users.pipeline.get_avatar', # This is a path of your pipeline.py
    #and get_avatar is the function.
)

然后将此内容添加到您的 pipeline.py 文件中

def get_avatar(backend, strategy, details, response,
        user=None, *args, **kwargs):
    url = None
    if backend.name == 'facebook':
        url = "http://graph.facebook.com/%s/picture?type=large"%response['id']
        # if you need a square picture from fb, this line help you
        url = "http://graph.facebook.com/%s/picture?width=150&height=150"%response['id']
    if backend.name == 'twitter':
        url = response.get('profile_image_url', '').replace('_normal','')
    if backend.name == 'google-oauth2':
        url = response['image'].get('url')
        ext = url.split('.')[-1]
    if url:
        user.avatar = url
        user.save()
于 2015-10-16T01:52:15.793 回答
0

我正在使用 vero4ka 建议的方法。

进入 python 调试 ( import pdb; pdb.set_trace()) 周围的行ext = url.split('.')[-1],我注意到拆分输出并没有完全分离文件扩展名,即:

(Pdb) url = response['image'].get('url').split('.')
(Pdb) url
[u'https://lh4', u'googleusercontent', u'com/redacted/redacted/photo', u'jpg?sz=50']

我也需要在?符号上分开。没什么大不了。

不知道为什么要拆分然后以这种方式重新组合扩展?

于 2014-11-20T17:57:10.207 回答
0

我对 Python Social Auth 不熟悉,但看起来您想要GooglePlusAuth

要获取图像 url,您必须向people.get API 方法发出 HTTP 请求,并将其userId设置为me并作为用户进行身份验证。响应包括一个image.url值。

于 2014-09-09T03:41:28.080 回答