简体   繁体   English

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

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

How can I retrieve profile picture and date of birth from google and facebook using python-social-auth by extending pipeline?如何通过扩展管道使用 python-social-auth 从 google 和 facebook 检索个人资料图片和出生日期? I've read that I can make functions to do so and set path to them but I don't know the attribute names that I must retrieve.我读过我可以创建函数并设置它们的路径,但我不知道必须检索的属性名称。 Please help!请帮忙!

To get avatars from social login, you need create a pipeline.py file in your app and add this lines to settings.py:要从社交登录中获取头像,您需要在您的应用程序中创建一个 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.
)

and later add this content to your pipeline.py file然后将此内容添加到您的 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()

Here's what I have used to save pictures for Facebook:这是我用来为 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() 

Save this function into a file, for instance, pipelines.py, and then add the function to your SOCIAL_AUTH_PIPELINE in your settings.将此函数保存到文件中,例如 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,
)

For Facebook you need to create your own Facebook app.对于 Facebook,您需要创建自己的 Facebook 应用程序。 You can only retrieve information and pictures from users who have given you the permission to do so.您只能从已授予您权限的用户那里检索信息和图片。 Same rules more or less apply for Google.相同的规则或多或少适用于 Google。 Read their API docs for more detail.阅读他们的 API 文档以获取更多详细信息。

The above answers may not work (it did not work for me) as the facebook profile URL does not work anymore without accesstoken.上述答案可能不起作用(它对我不起作用),因为如果没有访问令牌,facebook 个人资料 URL 将不再起作用。 The following answer worked for me.以下答案对我有用。

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'])

add to the pipeline in setting.py,添加到setting.py中的管道中,

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

Just to extend sadat's answer which works perfectly for saving the url.只是为了扩展萨达特的答案,它非常适合保存网址。 If you are wanting to save the actual image from the url to a django imagefield would need to do the below:如果您想将 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