簡體   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