如何在通过Facebook登录并将其保存在我的userprofile模型中时存储用户的Facebook个人资料图片。
我发现这个链接说明如何使用django-social-auth,https://gist.github.com/kalamhavij/1662930。但信号现已弃用,我必须使用管道。
任何想法如何使用python-social-auth和pipeline进行相同的操作?
答案 0 :(得分:19)
这就是我的工作方式。 (来自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',
)
答案 1 :(得分:6)
假设您已配置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',
)
答案 2 :(得分:1)
上述答案可能不起作用(它对我不起作用),因为如果没有访问令牌,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')