首页 > 解决方案 > 获取作为序列化对象发送的所请求用户的配置文件

问题描述

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

消费者.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

查询.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

标签: pythondjangodjango-channels

解决方案


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


推荐阅读