2021-03-07 18:15:29 +01:00
|
|
|
import json
|
2021-03-10 23:36:26 +01:00
|
|
|
from channels.generic.websocket import WebsocketConsumer
|
|
|
|
from django.template.loader import render_to_string
|
2021-03-12 00:09:19 +01:00
|
|
|
from apps.back.models import Post
|
2021-03-07 18:15:29 +01:00
|
|
|
|
2021-03-10 23:36:26 +01:00
|
|
|
class BlogConsumer(WebsocketConsumer):
|
2021-03-07 18:15:29 +01:00
|
|
|
|
|
|
|
def connect(self):
|
|
|
|
''' Cliente se conecta '''
|
|
|
|
# Recoge el nombre de la sala
|
|
|
|
self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
|
|
|
|
self.room_group_name = "blog_%s" % self.room_name
|
|
|
|
|
|
|
|
# Se une a la sala
|
2021-03-08 21:25:34 +01:00
|
|
|
self.channel_layer.group_add(self.room_group_name, self.channel_name)
|
2021-03-07 18:15:29 +01:00
|
|
|
|
|
|
|
# Informa al cliente del éxito
|
2021-03-08 21:25:34 +01:00
|
|
|
self.accept()
|
2021-03-07 18:15:29 +01:00
|
|
|
|
|
|
|
def disconnect(self, close_code):
|
|
|
|
''' Cliente se desconecta '''
|
|
|
|
# Leave room group
|
2021-03-08 21:25:34 +01:00
|
|
|
self.channel_layer.group_discard(self.room_group_name, self.channel_name)
|
2021-03-07 18:15:29 +01:00
|
|
|
|
|
|
|
def receive(self, text_data):
|
|
|
|
''' Cliente envía información y nosotros la recibimos '''
|
|
|
|
text_data_json = json.loads(text_data)
|
2021-03-12 00:09:19 +01:00
|
|
|
selector = text_data_json["selector"]
|
|
|
|
template = text_data_json["template"]
|
|
|
|
data = text_data_json["data"]
|
2021-03-07 18:15:29 +01:00
|
|
|
|
2021-03-12 00:09:19 +01:00
|
|
|
# Database
|
|
|
|
if template == "partials/blog/all_articles.html":
|
|
|
|
data["posts"] = Post.objects.all()[:5]
|
2021-03-07 18:15:29 +01:00
|
|
|
|
2021-03-12 00:09:19 +01:00
|
|
|
if template == "partials/blog/single.html":
|
|
|
|
data["post"] = Post.objects.get(data['id'])
|
2021-03-07 18:15:29 +01:00
|
|
|
|
|
|
|
# Send message to WebSocket
|
2021-03-08 21:25:34 +01:00
|
|
|
self.send(
|
2021-03-07 18:15:29 +01:00
|
|
|
text_data=json.dumps(
|
|
|
|
{
|
2021-03-12 00:09:19 +01:00
|
|
|
"selector": selector,
|
|
|
|
"html": render_to_string(template, data)
|
2021-03-07 18:15:29 +01:00
|
|
|
}
|
|
|
|
)
|
2021-03-12 00:09:19 +01:00
|
|
|
)
|