[파이썬] web2py에서의 실시간 알림

Web2py는 파이썬으로 작성된 웹 프레임워크로, 간결하고 신속한 웹 애플리케이션 개발을 위해 많은 기능을 제공합니다. 이 중에서도 실시간 알림은 사용자들이 웹 애플리케이션과 상호작용 할 때 중요한 기능입니다. web2py는 이를 위해 다양한 방법을 제공하며, 이번 글에서는 파이썬을 사용하여 실시간 알림을 구현하는 방법에 대해 알아보겠습니다.

장고 서버 설정

실시간 알림을 구현하기 위해서는 장고 서버에서 추가적인 설정이 필요합니다. 다음과 같이 channels 패키지를 설치합니다.

pip install channels

알림 모델 생성

실시간 알림을 저장하기 위한 모델을 생성합니다. models.py 파일에 다음 내용을 추가합니다.

class Notification(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    message = models.CharField(max_length=255)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.message

알림 생성 기능 구현

알림을 생성하고 실시간으로 사용자에게 알리기 위해 views.py 파일에 다음 코드를 추가합니다.

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
import json

def create_notification(request):
    user = request.user
    message = request.POST.get('message')
    
    notification = Notification.objects.create(user=user, message=message)
    
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        'notifications',
        {
            'type': 'send_notification',
            'message': json.dumps({
                'user': user.username,
                'message': message,
                'timestamp': notification.timestamp.strftime('%Y-%m-%d %H:%M:%S')
            })
        }
    )
    
    return JsonResponse({'status': 'success'})

실시간 알림 전송

알림을 생성하면 send_notification 메소드를 통해 해당 알림을 실시간으로 사용자에게 전송합니다. consumers.py 파일을 생성하고 다음 내용을 추가합니다.

from channels.generic.websocket import WebsocketConsumer
import json

class NotificationConsumer(WebsocketConsumer):
    def connect(self):
        self.group_name = 'notifications'
        async_to_sync(self.channel_layer.group_add)(
            self.group_name,
            self.channel_name
        )
        self.accept()

    def disconnect(self, close_code):
        async_to_sync(self.channel_layer.group_discard)(
            self.group_name,
            self.channel_name
        )

    def send_notification(self, event):
        message = json.loads(event['message'])
        self.send(text_data=json.dumps({
            'user': message['user'],
            'message': message['message'],
            'timestamp': message['timestamp']
        }))

뷰와 URL 매핑

마지막으로 urls.py 파일에 다음 내용을 추가하여 해당 뷰와 URL을 매핑합니다.

from django.urls import path
from myapp.views import create_notification
from myapp.consumers import NotificationConsumer

websocket_urlpatterns = [
    path('ws/notifications/', NotificationConsumer.as_asgi()),
]

urlpatterns = [
    # ...
    path('create_notification/', create_notification, name='create_notification'),
    # ...
]

결과 확인

이제 웹 애플리케이션에서 create_notification 엔드포인트를 호출하면 알림이 생성되고 실시간으로 사용자에게 전달됩니다. 클라이언트 측에서는 websocket을 통해 알림을 수신하고 화면에 표시하면 됩니다.

const socket = new WebSocket('ws://your-domain/ws/notifications/');

socket.onmessage = function(e) {
  const data = JSON.parse(e.data);
  // 알림을 화면에 표시
};

실시간 알림을 구현하는 것은 web2py에서 파이썬을 사용하여 쉽게 할 수 있는 일입니다. 위의 코드를 참고하여 웹 애플리케이션에 실시간 알림 기능을 추가해보세요. ```