使用python-social-auth将Facebook个人资料图片保存在模型中



如何在通过Facebook登录时存储用户的获取Facebook个人资料图片并将其保存在我的用户个人资料模型中。

我找到了这个链接,它说明了如何使用django-social-auth,https://gist.github.com/kalamhavij/1662930,但是信号现在已经弃用,我必须使用管道。

知道我如何使用python-social-auth和管道做同样的事情吗?

这就是它与我一起工作的方式。(从 https://github.com/omab/python-social-auth/issues/80)

将以下代码添加到 pipeline.py:

from requests import request, HTTPError
from django.core.files.base import ContentFile

def save_profile_picture(strategy, user, response, details,
                         is_new=False,*args,**kwargs):
    if is_new and strategy.backend.name == 'facebook':
        url = 'http://graph.facebook.com/{0}/picture'.format(response['id'])
        try:
            response = request('GET', url, params={'type': 'large'})
            response.raise_for_status()
        except HTTPError:
            pass
        else:
            profile = user.get_profile()
            profile.profile_photo.save('{0}_social.jpg'.format(user.username),
                                   ContentFile(response.content))
            profile.save()

并添加到 settings.py 中的管道:

SOCIAL_AUTH_PIPELINE += (
'<application>.pipelines.save_profile_picture',
)

假设您已经配置了SOCIAL_AUTH_PIPELINE,则与信号方法没有太大区别。

只需创建所需的管道(跳过所有导入,它们很明显)

def update_avatar(backend, details, response, social_user, uid,
                  user, *args, **kwargs):
    if backend.__class__ == FacebookBackend:
        url = "http://graph.facebook.com/%s/picture?type=large" % response['id']
        avatar = urlopen(url)
        profile = user.get_profile()
        profile.profile_photo.save(slugify(user.username + " social") + '.jpg', 
                            ContentFile(avatar.read()))              
        profile.save()

并添加到管道:

SOCIAL_AUTH_PIPELINE += (
    '<application>.pipelines.update_avatar',
)

上述答案可能不起作用(它对我不起作用),因为如果没有访问令牌,Facebook 个人资料 URL 将不再有效。以下答案对我有用。

def save_profile(backend, user, response, is_new=False, *args, **kwargs):
    if is_new and backend.name == "facebook":
    #The main part is how to get the profile picture URL and then do what you need to do
        Profile.objects.filter(owner=user).update(
            imageUrl='https://graph.facebook.com/{0}/picture/?type=large&access_token={1}'.format(response['id'],
                                                                                                  response[
                                                                                                      'access_token']))

添加到 setting.py 中的管道,

SOCIAL_AUTH_PIPELINE+ = ('<full_path>.save_profile')

最新更新