在python-social-auth中从google和facebook检索个人资料图片

Kes*_*wal 8 python django python-2.7 python-social-auth

如何通过扩展管道使用python-social-auth从google和facebook检索个人资料图片和出生日期?我已经读过我可以创建函数并设置它们的路径,但我不知道必须检索的属性名称.请帮忙!

Rob*_*lís 13

要从社交登录获取头像,您需要在应用中创建一个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 the path of your pipeline.py
    #and get_avatar is the function.
)
Run Code Online (Sandbox Code Playgroud)

然后将此内容添加到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 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()
Run Code Online (Sandbox Code Playgroud)


Jaa*_*kko 5

这是我用来为Facebook保存图片的方法:

def save_profile_picture(backend, user, response, details,
                         is_new=False,*args,**kwargs):

    if backend.__class__.__name__ == 'FacebookOAuth2':
        up = UserProperties.objects.get_or_create(user=user) #RETURNS TUPLE (instance, created(boolean))
        if not up[0].photo:
            url = 'http://graph.facebook.com/{0}/picture'.format(response['id'])
            response = urllib.request.urlopen(url)
            io = BytesIO(response.read())
            up[0].photo.save('profile_pic_{}.jpg'.format(user.pk), File(io))
            up[0].save() 
Run Code Online (Sandbox Code Playgroud)

将此函数保存到文件中,例如pipelines.py,然后将该函数添加到您设置中的SOCIAL_AUTH_PIPELINE.

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.social_auth.associate_by_email', 
    'social.pipeline.user.create_user',
    'social.pipeline.social_auth.associate_user',
    'social.pipeline.social_auth.load_extra_data',
    'social.pipeline.user.user_details',
    'projects.pipeline.save_profile_picture', #save facebook profile image,
)
Run Code Online (Sandbox Code Playgroud)

对于Facebook,您需要创建自己的Facebook应用程序.您只能从获得许可的用户处检索信息和图片.同样的规则或多或少适用于Google.阅读他们的API文档以获取更多详细信息.