Python社会认证获取Google头像
有没有办法用Python社交认证获取Google的头像网址?
我在处理Facebook和Twitter时是这样做的,添加一个处理流程,代码如下:
if strategy.backend.name == 'facebook':
url = 'http://graph.facebook.com/{0}/picture'.format(response['id'])
elif strategy.backend.name == "twitter":
if response['profile_image_url'] != '':
url = response['profile_image_url']
elif strategy.backend.name == "GoogleOAuth2": # doesn't work
user_id = response['id']
url = "???"
首先,我不知道后端的名字是不是“GoogleOAuth2”?
其次,我应该用什么网址来保存用户的头像呢?这样做可以吗?
4 个回答
我正在使用vero4ka建议的方法。
在大约这一行ext = url.split('.')[-1]
附近,我进入了python的调试模式(import pdb; pdb.set_trace()
),我注意到分割的结果没有完全把文件扩展名分开,比如:
(Pdb) url = response['image'].get('url').split('.')
(Pdb) url
[u'https://lh4', u'googleusercontent', u'com/redacted/redacted/photo', u'jpg?sz=50']
我还需要在?
符号上进行分割。没什么大不了的。
我不太明白为什么要先分割,然后再把扩展名组合起来呢?
我对Python Social Auth不太熟悉,但看起来你想要的是GooglePlusAuth。
要获取图片的链接,你需要向people.get API方法发送一个HTTP请求,里面的userId
要设置为me
,并且要以用户的身份进行认证。这样返回的结果中会包含一个image.url
的值。
要从社交登录获取头像,你需要在你的应用里创建一个叫做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 a 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 you need a square picture from fb, this line help you
url = "http://graph.facebook.com/%s/picture?width=150&height=150"%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()
在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在程序中使用这些数据。这个过程可能会涉及到很多步骤,比如读取文件、处理数据、然后输出结果。
有些时候,程序可能会因为一些错误而停止工作。这些错误可能是因为数据格式不对、文件找不到,或者其他一些原因。为了让程序更稳定,我们可以添加一些检查,确保在出错之前能够处理好这些问题。
另外,程序的运行速度也是一个需要考虑的因素。如果程序运行得很慢,可能会影响用户的体验。因此,我们需要优化代码,让它运行得更快。
总之,编程不仅仅是写代码,还包括如何处理数据、避免错误和提高效率。这些都是让程序更好用的重要方面。
from social.backends.google import GoogleOAuth2
def save_profile(backend, user, response, *args, **kwargs):
if isinstance(backend, GoogleOAuth2):
if response.get('image') and response['image'].get('url'):
url = response['image'].get('url')
ext = url.split('.')[-1]
user.avatar.save(
'{0}.{1}'.format('avatar', ext),
ContentFile(urllib2.urlopen(url).read()),
save=False
)
user.save()