python - 获取作为序列化对象发送的所请求用户的配置文件
问题描述
我将请求的用户对象发送到后台任务,该任务负责获取该用户的个人资料,然后计算个人资料的完整性。我可以发送序列化的用户对象,但无法获取该用户的个人资料。我该怎么做呢?
消费者.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
解决方案
最好只发送用户的 pk 并从消费者的数据库中检索它,因为这是跨进程传递的消息并尝试序列化模型对象不是一个好主意
推荐阅读
- flutter - 当某些包与某些平台不兼容时,如何在flutter中进行多平台开发?
- html - 用户注册表单中应该允许和拒绝哪些字符(姓名、地址、电话等)?
- python-3.x - 如何打印上一个打印行的更改?
- vue.js - 如何在 Nuxt Vue 的单个模板中添加多个组件?
- javascript - 与本地数据库交互的仪表板网站
- react-native - Socket Io 不使用反应钩子监听事件
- css - css动画被拉长了
- matrix - 如何将嵌套向量矩阵转换为嵌套向量向量
- python - Python:在异步函数中调用异步类
- mysql - 嗨,我如何使用 mysql 显示城市中薪酬第二高的员工