この記事は3年以上前に書かれた記事で内容が古い可能性があります
DjangoでChatアプリを作る4(チャットの投稿ができるまで)
2019-02-18
DjangoでChatアプリを作る3(チャットの投稿ができるまで)の続き
新規作成
% vim chat/consumers.py
% cat chat/consumers.py from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message }))
新規作成
% vim chat/routing.py
% cat chat/routing.py from django.conf.urls import url from . import consumers websocket_urlpatterns = [ url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer), ]
追記
% vim mysite/routing.py
% cat mysite/routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), })
チャット投稿ができた!