我一直在使用带有 django-channels 的 websockets 连接来构建具有以下路由的聊天室应用程序:
re_path(r'ws/chat/(?P<room_name>\w+)/participant/(?P<user>\w+)/$', consumers.ChatConsumer.as_asgi())
因此,如果我的聊天室的 id 是 1,要连接到 WS,我将使用以下 url,其中 2 是想要进入房间的参与者的 id:
ws/chat/1/participant/1/
现在我将房间模型的 id 更改为 UUID,因此现在要连接到房间,我需要使用以下网址
ws/chat/84f48468-e966-46e9-a46c-67920026d669/participant/1/
其中“84f48468-e966-46e9-a46c-67920026d669”现在是我房间的ID,但我收到以下错误:
raise ValueError("No route found for path %r." % path)
ValueError: No route found for path 'ws/chat/84f48468-e966-46e9-a46c-
67920026d669/participant/1/'.
WebSocket DISCONNECT /ws/chat/84f48468-e966-46e9-a46c-67920026d669/participant/1/
[127.0.0.1:50532]
我的消费者:
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.user = self.scope['url_route']['kwargs']['user']
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, close_code):
delete = delete_participant(self.room_name, self.user)
if delete == 'not_can_delete_user':
pass
else:
# Leave room group
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
f'chat_{self.room_name}',
{
'type': 'receive',
'message': "USER_DISCONNECT",
'body': {
'participant': delete,
'idParticipant': self.user
}
}
)
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
def receive(self, text_data=None, type='receive', **kwargs):
if isinstance(text_data, dict):
text_data_json = text_data
message = text_data_json['message']
body = text_data_json['body']
else:
text_data_json = json.loads(text_data)
message = text_data_json['message']
body = text_data_json['body']
self.send(text_data=json.dumps({
'message': message,
"body": body
}))
出了什么问题?
尝试这个正则表达式:
re_path(r'ws/chat/(?P<room_name>[A-Za-z0-9_-]+)....
格式化组 ID 并删除“-”,将其传递到 JavaScript 中并使用 groupId2 代替。
groupId2 = groupId.replaceAll("-","");
我认为这比搜索正则表达式更好,问题是 django uuid 字段是 32 字节而不是 36 字节,因为它与 '-' 一样。
因此阅读完整日志将显示出现了值错误。
websocket_urlpatterns = [
re_path(
r"ws/bar/(?P<trip_id>[A-Za-z0-9_-]+)/$",
consumers.ProgressBarConsumer.as_asgi(),
),
]
这应该可以正常工作!