如何解决django:在websocket上更新模型值
所以我将用户模型扩展到此
class ProfileImage(models.Model):
"""
Profile model
"""
user = models.OneToOneField(
verbose_name=_('User'),#to=settings.AUTH_USER_MODEL,to = User,related_name='profile',on_delete=models.CASCADE
)
avatar = models.ImageField(upload_to='profile_image')
notifications = models.FloatField(default='0')
通知值是0,但是我想要的是在收到网络套接字时给通知+1,那么当收到消息时我该怎么做?这是我的消费者。py
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self,event):
print("connected",event)
other_user = self.scope['url_route']['kwargs']['username']
me = self.scope['user']
# print(other_user,me)
thread_obj = await self.get_thread(me,other_user)
self.thread_obj = thread_obj
chat_room = f"thread_{thread_obj.id}"
self.chat_room = chat_room
await self.channel_layer.group_add(
chat_room,self.channel_name
)
await self.send({
"type": "websocket.accept"
})
# await asyncio.sleep(10)
async def websocket_receive(self,event):
# when a message is received from the websocket
print("receive",event)
front_text = event.get('text',None)
if front_text is not None:
loaded_dict_data = json.loads(front_text)
msg = loaded_dict_data.get('message')
user = self.scope['user']
username = 'default'
if user.is_authenticated:
username = user.username
myResponse = {
'message': msg,'username': username,}
await self.create_chat_message(user,msg)
# broadcast the message event to be send
await self.channel_layer.group_send(
self.chat_room,{
"type": "chat_message","text": json.dumps(myResponse)
}
)
async def chat_message(self,event):
# sends the actual message
await self.send({
"type": "websocket.send","text": event['text']
})
async def websocket_disconnect(self,event):
# when the socket connects
print("disconnected",event)
@database_sync_to_async
def get_thread(self,user,other_username):
return Thread.objects.get_or_new(user,other_username)[0]
@database_sync_to_async
def create_chat_message(self,me,msg):
thread_obj = self.thread_obj
return ChatMessage.objects.create(thread=thread_obj,user=me,message=msg)
我该怎么做?,我认为可以通过websocket接收来完成,但是我尝试并且不能,谢谢您的帮助
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。