django - 如何使用 social-auth-app-django 获取 gmail 社交头像
问题描述
我用谷歌搜索并获得了一些有用的链接来获取 gmail 头像。我使用了 social-auth-app-django库并按照 链接设置功能。身份验证工作正常,但卡在获取头像。我在项目主配置的根目录中创建了pipeline.py,并在我的视图中调用了它,就像from TestDjangoAuth.pipeline import get_avatar 一样。这是我检索头像的正确方法吗?另一个查询是如何使用 views.py 中的管道方法,例如我们在SOCIAL_AUTH_PIPELINE中调用的user_details、get_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'
解决方案
我终于通过谷歌搜索并应用了一些修改,使用下面的代码片段解决了我的问题。
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')
推荐阅读
- angular - ngx-translate-core 无法翻译 ng-container 元素
- algorithm - 检查 3 个相同房间的单个会议室时间表可用性的方法或算法?
- django - 在视图中访问自定义用户模型的字段
- c# - 时间跨度自定义模型活页夹
- c# - 如何检查文件夹或文件是否被锁定、打开或正在使用
- c# - 在 SSIS 中访问 C# 中的 Excel 单元格
- c++ - C++ lambda 按值捕获语义和允许的优化
- python - 在 Python 中实现广义生日悖论
- python - Python:将许多具有共享键的字典(在 JSON 中)连接到一个大字典中
- c++ - 编译时是否需要动态库