Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python social auth中从google和facebook检索个人资料图片_Python_Django_Python 2.7_Python Social Auth - Fatal编程技术网

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

在python social auth中从google和facebook检索个人资料图片,python,django,python-2.7,python-social-auth,Python,Django,Python 2.7,Python Social Auth,如何通过扩展管道使用python social auth从google和facebook检索个人资料图片和出生日期?我已经读到,我可以让函数这样做,并设置它们的路径,但我不知道我必须检索的属性名称。请帮忙 以下是我用来为Facebook保存图片的方法: def save_profile_picture(backend, user, response, details, is_new=False,*args,**kwargs): if b

如何通过扩展管道使用python social auth从google和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() 
将此函数保存到文件(例如pipelines.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.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应用程序。您只能从授予您权限的用户检索信息和图片。同样的规则或多或少也适用于谷歌。阅读他们的API文档以了解更多详细信息。

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

上述答案可能不起作用(对我来说不起作用),因为如果没有accesstoken,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')
SOCIAL\u AUTH\u PIPELINE+=(“.save\u profile”)

仅扩展sadat的答案,该答案非常适合保存url。如果要将实际图像从url保存到django imagefield,需要执行以下操作:

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()

所以我的理解是,我必须找到一个Google+为其图像提供服务的URL,并使用该URL检索个人资料图片,然后覆盖我的管道。我做对了吗?是的。阅读他们的文档了解更多详细信息。您需要将函数添加到管道中的正确位置,以获得所需的行为。对于那个投了反对票的人:我给了一个很好的答案:如何开始。你不能期望人们为其他人编写整个程序,而是给出正确的答案,就像这里的情况一样。不幸的是,这种负面影响在这里非常猖獗。我还有一个疑问,我有一个自定义模型,它继承了Django.contrib.author的用户模型,然后还有两个DOB和profile picture字段。当我使用OAuth2登录Google时,admin面板中的django.contrib.auth.user获得了它的值,但我的自定义模型没有与之一一链接。有没有关于我如何做到这一点的建议?谷歌现在似乎需要一个api请求
GEThttps://www.googleapis.com/plus/v1/people/userId
,它将返回包含请求图像的json响应。查看此内容访问
graph.facebook.com
时确保使用HTTPS而不是HTTP访问
graph.facebook.com