# apps/common/services/notification_service.py import logging from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from apps.notification.models import Notification logger = logging.getLogger(__name__) class NotificationService: def send_notification(self, user, title, content, notification_type, related_object_id, sender=None): """发送通知并通过WebSocket推送""" try: notification = Notification.objects.create( sender=sender, receiver=user, title=title, content=content, type=notification_type, related_resource=related_object_id, ) # 准备发送到WebSocket的数据 notification_data = { "id": str(notification.id), "title": notification.title, "content": notification.content, "type": notification.type, "created_at": notification.created_at.isoformat(), } # 只有当sender不为None时才添加sender信息 if notification.sender: notification_data["sender"] = { "id": str(notification.sender.id), "name": notification.sender.name } channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( f"notification_user_{user.id}", { "type": "notification", "data": notification_data } ) return notification except Exception as e: logger.error(f"发送通知失败: {str(e)}") return None