GRS*_*GRS 1 python django facebook-graph-api django-rest-framework django-oauth
这个问题是关于使用https://github.com/PhilipGarnero/django-rest-framework-social-oauth2库自动在 Django 模型中保存 Facebook 个人资料图片。
编辑:
有两种方法可以解决这个问题:将图像的 URLCharField()
保存在或使用ImageField()
. 两种解决方案都可以。
上面的库允许我使用不记名令牌创建和验证用户。我已经创建了配置文件模型:
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userprofile')
photo = models.FileField(blank=True) # OR
######################################
url = 'facebook.com{user id}/picture/'
photo = models.CharField(default=url)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.userprofile.save()
Run Code Online (Sandbox Code Playgroud)
它会自动为每个用户创建用户配置文件。现在,我想添加以下代码来保存 Facebook 中的照片。Facebook API 需要 user id
获取此图片。
photo = 'https://facebook/{user-id}/picture/'
UserProfile.objects.create(user=instance, photo=photo)
Run Code Online (Sandbox Code Playgroud)
以上不起作用,因为
1)我不知道从哪里得到user id
。
2)图像不能这样存储,我需要将其转换为字节或其他方法。
有一个非常简单的解决方案。使用python-social-auth 管道。
这个东西的工作方式就像middleware
,你可以在你的设置页面中添加SOCIAL_AUTH_PIPELINE
一个函数,该函数将在每次用户使用social_django
.
一个例子:
在您的设置页面中,添加以下内容:
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',
'home.pipeline.save_profile',
)
Run Code Online (Sandbox Code Playgroud)
看home.pipeline.save_profile
,这是home.pipeline
文件中的新管道。(将其更改为您自己的用户模块文件夹)
在那里 ( home.pipeline
) 添加以下内容:
from .models import UserProfile
def save_profile(backend, user, response, *args, **kwargs):
if backend.name == "facebook":
UserProfile.objects.create(
user=user,
photo_url=response['user']['picture']
)
Run Code Online (Sandbox Code Playgroud)
这是一个例子。如果用户已经登录,您需要更改它以获取/更新。此外,尝试使用该response
参数,您可以在那里使用不同的数据。
最后一件事,请确保将picture
属性添加到您的设置中:
SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {
'fields': 'id, name, email, picture'
}
Run Code Online (Sandbox Code Playgroud)
http://python-social-auth.readthedocs.io/en/latest/backends/facebook.html
https://godjango.com/122-custom-python-social-auth-pipeline/
https://github.com/python-social-auth/social-app-django
归档时间: |
|
查看次数: |
1260 次 |
最近记录: |