225번째 줄: |
225번째 줄: |
| |/chat/routing.py 작성 | | |/chat/routing.py 작성 |
| |<syntaxhighlight lang="python"> | | |<syntaxhighlight lang="python"> |
− | from django.conf.urls import url | + | from django.urls import re_path |
| + | |
| from . import consumers | | from . import consumers |
| | | |
| websocket_urlpatterns = [ | | websocket_urlpatterns = [ |
− | url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer), | + | re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()), |
| ] | | ] |
| </syntaxhighlight> | | </syntaxhighlight> |
| |- | | |- |
| |라우팅 등록 | | |라우팅 등록 |
− | |/routing.py 수정 | + | |channels를 설치하며 작성한 agsi.py 안에 내용을 채워준다. |
| chat 안의 라우팅을 등록해준다. | | chat 안의 라우팅을 등록해준다. |
| | | |
− | 그리고 임포트하는 모듈을 수정해준다. | + | 그리고 이를 사용하기 위한 라이브러리를 불러온다. |
| |<syntaxhighlight lang="python"> | | |<syntaxhighlight lang="python"> |
| + | ...... |
| + | |
| + | from channels.routing import URLRouter |
| + | from channels.security.websocket import AllowedHostsOriginValidator |
| from channels.auth import AuthMiddlewareStack | | from channels.auth import AuthMiddlewareStack |
− | from channels.routing import ProtocolTypeRouter, URLRouter
| |
| import chat.routing | | import chat.routing |
| | | |
− | application = ProtocolTypeRouter({ | + | application = ProtocolTypeRouter( |
− | # (http->django views is added by default)
| + | { |
− | 'websocket': AuthMiddlewareStack(
| + | "http": django_asgi_app, |
− | URLRouter(
| + | "websocket": AllowedHostsOriginValidator( |
− | chat.routing.websocket_urlpatterns
| + | AuthMiddlewareStack(URLRouter(chat.routing.websocket_urlpatterns)) |
− | ) | + | ), |
− | ), | + | } |
− | })
| + | ) |
| </syntaxhighlight> | | </syntaxhighlight> |
− | |}여기까지 하고 채팅을 쳐 보면... 채팅이 나와야 정상. | + | |}여기까지 하고 점검해보자. /chat/lobby/ 에 접속한 후 채팅을 치면 떠야 한다. |
| + | |
| + | 같은 브라우저를 띄워두고 한쪽에서 채팅을 치면 다른 쪽에서 안뜨는데, 다른 브라우저에선 안뜬다. 접속한 모두에게 반영될 수 있도록 채널레이어를 구현한다. |
| | | |
| | | |