获取作为序列化对象发送的请求用户的配置文件

时间:2019-03-30 10:00:31

标签: python django django-channels

我正在将请求的用户对象发送到后台任务,该任务负责获取该用户的个人资料,然后计算个人资料的完整性。我可以发送序列化的用户对象,但无法获取该用户的配置文件。我该怎么办?

consumers.py

class AccountBackgroundTasks(SyncConsumer):
  def calculate_profile_percentage(self, context):
        print("arrived here successfully")
        logger.info("context", context)
        weight = {'full_name': 10, 'age': 10, 'city': 10, 'address': 10}
        total = 0
        try:
            user = context.get('user')
            profile_instance = model_to_dict(Profile.objects.get(user=user))
            for field in profile_instance:
                try:
                    total += weight[field]
                except AttributeError:
                    logger.error("Could not find the field")
                    continue
        except Profile.DoesNotExist:
            logger.error("Profile does not exist")
            return
        return total

query.py

@staticmethod
def resolve_profile(self, info, **kwargs):
    print('info', info.context.user)
    # type <class 'apps.accounts.models.User'>
    print('type', type(info.context.user))
    if info.context.user.is_authenticated:
        channel_layer = get_channel_layer()
        print("channel_layer", channel_layer)
        async_to_sync(channel_layer.send)('accounts', {
            'type': 'calculate.profile.percentage',
            'text': serializers.serialize('json', [info.context.user, ])
        })
        return Profile.objects.get(user=info.context.user)
    return None

1 个答案:

答案 0 :(得分:1)

最好只是发送用户的pk并从使用者的db中检索它,因为这是一条跨进程传递的消息,并且尝试序列化模型对象不是一个好主意