简体   繁体   English

如何在Django和Angular中使用websockets使用用户ID发送和接收消息的方式正确完成?

[英]How it should be done properly to send and receive message with user ID using websockets in Django and Angular?

I am going to create chatbot using websockets. 我将使用websockets创建chatbot。 Each user can have their own account. 每个用户可以拥有自己的帐户。 I have Django backend and frontend written in Angular. 我有用Angular编写的Django后端和前端。 At the moment I have a problem with message object. 目前,我对消息对象有问题。 To wit I get this in backend: 智慧地说,我在后端得到这个:

django_1  | django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint
django_1  | DETAIL:  Failing row contains (212, {"message":"Hello"}, null).

It looks as I wouldn't send user ID from frontend. 看来我不会从前端发送用户ID。 Maybe I should send something like this {"message":"Hello", "id":1} ? 也许我应该发送类似以下内容的{"message":"Hello", "id":1}吗? I wonder how can I solve it and how it should be done properly? 我想知道如何解决它,以及如何正确完成它?

My Django message model looks in this way: 我的Django消息模型看起来是这样的:

class Message(models.Model):
    user = models.ForeignKey('auth.User')
    message = models.CharField(max_length=200)

This is my backend consumer: 这是我的后端使用者:

@channel_session_user_from_http
def msg_consumer(message):
    text = message.content.get('text')
    Message.objects.create(
        message=text,
    )
    Group("chat").send({'text': text})

@channel_session_user
def ws_connect(message):
    # Accept the connection
    message.reply_channel.send({"accept": True})
    # Add to the chat group
    Group("chat").add(message.reply_channel)

    message.reply_channel.send({
        "text": json.dumps({
            'message': 'Welcome'
        })
    })

@channel_session_user
def ws_receive(message):

    message.reply_channel.send({"accept": True})
    print("Backend received message: " + message.content['text'])
    Message.objects.create(
        message = message.content['text'],
    )

    Channel("chat").send({
        "text": json.dumps({
             'message': 'Can we start?'
         })
    })

@channel_session_user
def ws_disconnect(message):
    Group("chat").discard(message.reply_channel)

This is part of my Angular component: 这是我的Angular组件的一部分:

export class HomeComponent {

    response: string;
    response2: string;

    constructor(
        private chatService: ChatService,
        private router: Router,
        private http: Http,
    ) {

        chatService.messages.subscribe(msg => {
            this.response = msg.message;
      console.log("Response from backend: " + msg.message);
        });

    }
    private message = {
        message: 'this is a test message'
    }

  sendMsg() {
        console.log('new message from client to websocket: ', this.message);
        this.chatService.messages.next(this.message);
        return this.message.message;
    }

  send(msg) {
     this.message.message = msg;
     this.sendMsg();
  }

      login() {
        return this.http.get('/data', )
            .map(response => response.json())
            .subscribe(response2 => this.response2 = response2);
    }


}

@Component({
  selector: 'key-up3',
  template: `
    <input #box (keyup.enter)="keyup7.emit(box.value)">
    <p>{{value}}</p>
  `
})
export class KeyUpComponent_v3 {
   @Output() keyup7 = new EventEmitter<string>();
}

UPDATE At the moment I solved it in the way shown below in backend. 更新目前,我已按照以下后端所示的方式解决了它。

def ws_receive(message): def ws_receive(消息):

message.reply_channel.send({"accept": True})
print("Backend received message: " + message.content['text'])
data = json.loads(message.content['text'])

Message.objects.create(
    user_id=data['user_id'],
    message = data['message'],
)

Error seems to indicate your Message instance was created without user_id . 错误似乎表明您的Message实例是在没有user_id情况下创建的。 What if you add this argument when creating a new Message instance ? 如果在创建新的Message实例时添加此参数怎么办?

@channel_session_user_from_http
def msg_consumer(message):
    text = message.content.get('text')
    Message.objects.create(
        user=message.user,  # <- Here is the user associated
        message=text,
    )
    Group("chat").send({'text': text})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM