![](/img/trans.png)
[英]Retrieving profile picture from google and facebook in python-social-auth
[英]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.