WebSocket과 HTTP, SSE
WebSocket과 HTTP,SSE 모두 응용계층에서 사용되는 프로토콜이다. HTTP는 클라이언트-서버 간의 통신을 위한 단방향 통신이고 SSE는 서버에서 클라이언트 통신을 위한 일방향 통신다. 그리고 WebSocket는
jongseoung.tistory.com
알림 기능에서 SSE를 사용하는 이유는 위에 포스팅에 작성해 두었다.
Django에서 알람 기능을 구현한 레퍼런스가 많이 없어서 정말 힘들었다. Django channels도 한번 구현해 보았지만 내가 원하는 결과와는 조금 달랐고 Django eventstream이라는 라이브러리가 있다고 해서 찾아보았지만 레퍼런스도 없고 문서, 리드미파일도 업데이트가 안되어있어서 코드를 하나하나 뜯어보는 고생을 했다.
이번글에서는 ASGI/Channels 설정을 하고 구현내용은 다음글에서 진행된다.
패키지 설치
우선 설치해야하는 패키지로는 3가지가 있는데 나는 pipenv를 사용하므로 pipenv 기준으로 작성했다.
pipenv install channels==3.0.5
pipenv install daphne
pipenv install django-eventstream
여기서 주의 깊게 봐야 할 점이 channels의 버전이 3.0.5라는 것이다.
django-eventstream 공식 문서를 보고 따라 하면 channels를 최신 버전을 다운로드하게 되는데 eventstream는 공식 문서를 업데이트되지 않았다.
앱 생성
python3 manage.py startapp alarm
Settings.py
# weheproject/settings.py
INSTALLED_APPS = [
"channels",
"django_eventstream",
....,
"alarms",
]
MIDDLEWARE = [
'django_grip.GripMiddleware',
...,
]
ASGI_APPLICATION = "weheproject.asgi.application"
EVENTSTREAM_STORAGE_CLASS = 'django_eventstream.storage.DjangoModelStorage'
asgi.py
"""
ASGI config for weheproject project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from channels.auth import AuthMiddlewareStack
from django.urls import path, re_path
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import django_eventstream
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "weheproject.settings")
django_asgi_app = get_asgi_application()
application = ProtocolTypeRouter(
{
'http': URLRouter([
path('events/<user_id>/', AuthMiddlewareStack(
URLRouter(django_eventstream.routing.urlpatterns)
), {'format-channels': ['user-{user_id}']}),
re_path(r'', get_asgi_application()),
]),
}
)
나는 알림의 고유 번호를 user_id를 사용했다.
Urls.py
from django.urls import path, include
urlpatterns = [
...,
path('api/v1/alarm/', include('alarms.urls')),
...,
]
결과
이후 아래처럼 ASGI/Channels로 변경이 되었다면 정상적으로 잘 된것이다. 이 부분 역시 제대로 진행되지 않아서 위 내용을 중간중간 계속 서버를 실행하면서 확인하였다.

Reference
GitHub - fanout/django-eventstream: Server-Sent Events for Django
Server-Sent Events for Django. Contribute to fanout/django-eventstream development by creating an account on GitHub.
github.com
ModuleNotFoundError: No module named 'channels.http'
I found a couple of similar questions, but nothing really helped. I tried updating asgiref version and also updated channels and django-eventstream. I mainly followed the instruction from the django-
stackoverflow.com
'Django > DRF' 카테고리의 다른 글
Django 프로젝트 단계별 가이드라인 1 (0) | 2023.11.23 |
---|---|
Django SSE 이용해서 알람 기능 구현 (2) (1) | 2023.10.19 |
DRF 구글 소셜로그인 TypeError: string indices must be integers (0) | 2023.10.12 |
DRF Paginator를 이용한 페이지네이션 (0) | 2023.10.11 |
DRF 유저 정보로 JWT 토큰 발급 (0) | 2023.10.11 |
WebSocket과 HTTP, SSE
WebSocket과 HTTP,SSE 모두 응용계층에서 사용되는 프로토콜이다. HTTP는 클라이언트-서버 간의 통신을 위한 단방향 통신이고 SSE는 서버에서 클라이언트 통신을 위한 일방향 통신다. 그리고 WebSocket는
jongseoung.tistory.com
알림 기능에서 SSE를 사용하는 이유는 위에 포스팅에 작성해 두었다.
Django에서 알람 기능을 구현한 레퍼런스가 많이 없어서 정말 힘들었다. Django channels도 한번 구현해 보았지만 내가 원하는 결과와는 조금 달랐고 Django eventstream이라는 라이브러리가 있다고 해서 찾아보았지만 레퍼런스도 없고 문서, 리드미파일도 업데이트가 안되어있어서 코드를 하나하나 뜯어보는 고생을 했다.
이번글에서는 ASGI/Channels 설정을 하고 구현내용은 다음글에서 진행된다.
패키지 설치
우선 설치해야하는 패키지로는 3가지가 있는데 나는 pipenv를 사용하므로 pipenv 기준으로 작성했다.
pipenv install channels==3.0.5
pipenv install daphne
pipenv install django-eventstream
여기서 주의 깊게 봐야 할 점이 channels의 버전이 3.0.5라는 것이다.
django-eventstream 공식 문서를 보고 따라 하면 channels를 최신 버전을 다운로드하게 되는데 eventstream는 공식 문서를 업데이트되지 않았다.
앱 생성
python3 manage.py startapp alarm
Settings.py
# weheproject/settings.py
INSTALLED_APPS = [
"channels",
"django_eventstream",
....,
"alarms",
]
MIDDLEWARE = [
'django_grip.GripMiddleware',
...,
]
ASGI_APPLICATION = "weheproject.asgi.application"
EVENTSTREAM_STORAGE_CLASS = 'django_eventstream.storage.DjangoModelStorage'
asgi.py
"""
ASGI config for weheproject project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
"""
import os
from channels.auth import AuthMiddlewareStack
from django.urls import path, re_path
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import django_eventstream
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "weheproject.settings")
django_asgi_app = get_asgi_application()
application = ProtocolTypeRouter(
{
'http': URLRouter([
path('events/<user_id>/', AuthMiddlewareStack(
URLRouter(django_eventstream.routing.urlpatterns)
), {'format-channels': ['user-{user_id}']}),
re_path(r'', get_asgi_application()),
]),
}
)
나는 알림의 고유 번호를 user_id를 사용했다.
Urls.py
from django.urls import path, include
urlpatterns = [
...,
path('api/v1/alarm/', include('alarms.urls')),
...,
]
결과
이후 아래처럼 ASGI/Channels로 변경이 되었다면 정상적으로 잘 된것이다. 이 부분 역시 제대로 진행되지 않아서 위 내용을 중간중간 계속 서버를 실행하면서 확인하였다.

Reference
GitHub - fanout/django-eventstream: Server-Sent Events for Django
Server-Sent Events for Django. Contribute to fanout/django-eventstream development by creating an account on GitHub.
github.com
ModuleNotFoundError: No module named 'channels.http'
I found a couple of similar questions, but nothing really helped. I tried updating asgiref version and also updated channels and django-eventstream. I mainly followed the instruction from the django-
stackoverflow.com
'Django > DRF' 카테고리의 다른 글
Django 프로젝트 단계별 가이드라인 1 (0) | 2023.11.23 |
---|---|
Django SSE 이용해서 알람 기능 구현 (2) (1) | 2023.10.19 |
DRF 구글 소셜로그인 TypeError: string indices must be integers (0) | 2023.10.12 |
DRF Paginator를 이용한 페이지네이션 (0) | 2023.10.11 |
DRF 유저 정보로 JWT 토큰 발급 (0) | 2023.10.11 |