简体   繁体   中英

Django channels, AttributeError

I'm trying to learn how to send messages over a websocket using channels 2.

I'm trying just to send a simple message when a client connects but I keep getting Attribute Errors:

class CameraOnlineConsumer(JsonWebsocketConsumer):
    def connect(self):
        self.accept()
        return self.send({
            "type": "websocket.accept",
            "send": {'a': "Hi"}
        })

raises:

self.sendMessage(content.encode("utf8"), binary)
AttributeError: 'dict' object has no attribute 'encode'
WebSocket DISCONNECT /ws/camera_online/connect [127.0.0.1:36006]

changing to:

 return self.send({
            "type": "websocket.accept",
            "send": "Hi"
        })

for example, returns the same error.

Try convert it to json like this ..


 import json    
    class CameraOnlineConsumer(JsonWebsocketConsumer):
            def connect(self):
                self.accept()
                return self.send(json.dumps({
                    "type": "websocket.accept",
                    "send": {'a': "Hi"}
                }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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