首页 > 解决方案 > 如何使用 social-auth-app-django 获取 gmail 社交头像

问题描述

我用谷歌搜索并获得了一些有用的链接来获取 gmail 头像。我使用了 social-auth-app-django库并按照 链接设置功能。身份验证工作正常,但卡在获取头像。我在项目主配置的根目录中创建了pipeline.py,并在我的视图中调用了它,就像from TestDjangoAuth.pipeline import get_avatar 一样。这是我检索头像的正确方法吗?另一个查询是如何使用 views.py 中的管道方法,例如我们在SOCIAL_AUTH_PIPELINE中调用的user_detailsget_username

这是 views.py 中的重定向方法,它给出了一些错误。我想将头像设置为会话:

from TestDjangoAuth.pipeline import get_avatar
def social_login(request):
    if request.method == 'GET':
        if request.user.is_authenticated:
            request.session['photo'] = get_avatar()

这是我修改以在我的视图中使用的pipeline.py

def get_avatar(backend, strategy, details, response, user=None, *args, **kwargs):
    url = None
    if backend.name == 'google-oauth2':
        url = response['image'].get('url')

    print(url)
    return url

当我返回 url 以在我的视图中使用以使用个人资料图片时,会出现以下错误

AttributeError at /auth/complete/google-oauth2/

'str' object has no attribute 'backend'

标签: djangopython-3.xdjango-socialauth

解决方案


我终于通过谷歌搜索并应用了一些修改,使用下面的代码片段解决了我的问题。

def get_avatar(request, 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':
        try:
            url = response["picture"]
        except KeyError:
            url = response['image'].get('url')

        get_file = download(url)
        file_name = url.split('/')[-1]
        extension = 'jpeg'

        f = BytesIO(get_file)
        out = BytesIO()

        image = Image.open(f)
        image.save(out, extension)

def download(url):
    try:
        r = requests.get(url)
        if not r.status_code == 200:
            raise Exception('file request failed with status code: ' + str(r.status_code))
        return (r.content)
    except Exception as ex:
        return ('error')

推荐阅读