DjangoでChatアプリを作る4(チャットの投稿ができるまで) | www.yoshiislandblog.net
Close

DjangoでChatアプリを作る4(チャットの投稿ができるまで)

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
        )
    ),
})

チャット投稿ができた!

DjangoでChatアプリを作る5(チャットの投稿が別画面でもリアルタイムに反映されるまで)に続く

%d bloggers like this: