繁体   English   中英

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

[英]Retrieving profile picture from google and facebook in python-social-auth

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

要从社交登录中获取头像,您需要在您的应用程序中创建一个 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.
)

然后将此内容添加到您的 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()

这是我用来为 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() 

将此函数保存到文件中,例如 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,
)

对于 Facebook,您需要创建自己的 Facebook 应用程序。 您只能从已授予您权限的用户那里检索信息和图片。 相同的规则或多或少适用于 Google。 阅读他们的 API 文档以获取更多详细信息。

上述答案可能不起作用(它对我不起作用),因为如果没有访问令牌,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']))
    elif backend.name == 'google-oauth2':
        if is_new and response.get('picture'):
            Profile.objects.filter(owner=user).update(imageUrl=response['picture'])

添加到setting.py中的管道中,

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

只是为了扩展萨达特的答案,它非常适合保存网址。 如果您想将 url 中的实际图像保存到 django 图像字段,则需要执行以下操作:

import requests
from io import BytesIO
from django.core import files

def save_profile(backend, user, response, is_new=False, *args, **kwargs):
if is_new and backend.name == "facebook":
    
    picture_url='https://graph.facebook.com/{0}/picture/?type=large&access_token={1}'.format(response['id'],
                                                                                              response[
                                                                                                  'access_token']))   
    file_name = f"{uuid.uuid4()}.jpeg"
            resp = requests.get(picture_url)
            if resp.status_code == requests.codes.ok:
                fp = BytesIO()
                fp.write(resp.content)
  
                profile.image.save(file_name, files.File(fp))
                profile.save()

暂无
暂无

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

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