일지
2023.06.12
scarlet0star
2023. 6. 13. 02:22
#asgi.py
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": TokenAuthMiddleware(
URLRouter([
]),
),
})
#consumers.py
class Consumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
async def disconnect(self, close_code):
async def receive(self, text_data):
await self.channel_layer.group_send
django channel 구현 첫번째 정리하기.
먼저 django channel은 각 앱에서 consumer를 구성한뒤 메인 프로젝트에 존재하는 asgi.py에서 routing 하는 것으로 구성한다. websocket은 기존 asgi 위에서 실행되기 때문이라고... 한다... 아직 잘 이해는 못했지만 기존 wsgi와 달리 비동기 서버 게이트웨이 인터페이스에서만 돌아가는 것으로 알고 있다. 실제로도 consumer들도 비동기 함수들이고 말이다.
consumer는 connect, disconnect, receive로 기본적으로 구성되며 그 외의 별도의 함수를 비동기로 정의하여 사용할 수 있다. 나는 signal을 이용하여 임의로 정의한 함수를 불러왔는데 예시코드를 뜯어 고쳤을 때는 아래와 같았다.
@receiver(post_save, sender=Comment)
def send_notification(sender, instance, created, **kwargs):
if created:
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
f"user_{instance.post.user.id}",
{
"type": "notify", # Calls NotificationConsumer.notify
"event": "New Comment",
"nickname": instance.user.nickname,
"comment_id": instance.content,
"post_id": instance.post.title,
},
)
그러니까 중요한 것은 type에 함수명을 지정해주는 것이다. 채널레이어나 언더바들이 포함된 메서드들... 내일 더 공부할 내용이다. 아직 이해가 되지 않았다.