繁体   English   中英

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

[英]Save facebook profile picture in model using python-social-auth

如何在通过 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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM