Browse Source

Conexão VueJS-Websocket

Websocket_painel
AlGouvea 3 years ago
parent
commit
ef69abb979
  1. 21
      frontend/src/__apps/painel/main.js
  2. 2
      sapl/celery.py
  3. 16
      sapl/painel/consumers.py
  4. 4
      sapl/painel/routing.py
  5. 29
      sapl/painel/tasks.py
  6. 2
      sapl/painel/urls.py
  7. 4
      sapl/painel/views.py
  8. 12
      sapl/settings.py

21
frontend/src/__apps/painel/main.js

@ -17,7 +17,7 @@ const v = new Vue({ // eslint-disable-line
el: '#app-painel',
data () {
return {
message: 'Hello VueJUS', // TODO: remove when porting to VueJS is done
message: null, // TODO: remove when porting to VueJS is done
polling: null,
painel_aberto: true,
sessao_plenaria: '',
@ -45,6 +45,7 @@ const v = new Vue({ // eslint-disable-line
resultado_votacao_css: '',
tipo_resultado: '',
tipo_votacao: '',
teste: null,
running: 0
}
},
@ -251,7 +252,7 @@ const v = new Vue({ // eslint-disable-line
this.fetchData()
this.polling = setInterval(() => {
console.info('Fetching data from backend')
// console.info('Fetching data from backend')
this.fetchData()
}, 100)
}
@ -261,6 +262,22 @@ const v = new Vue({ // eslint-disable-line
clearInterval(this.polling)
},
created () {
const socket = new WebSocket(`ws://${window.location.host}/ws/painel/`)
socket.onopen = function (e) {
console.log('Connection established')
}
socket.onclose = function (e) {
console.error('Ws fechou!')
}
socket.onmessage = function (e) {
console.log('got to onmessage')
// this.teste = JSON.parse(e.data)
// console.log(this.teste)
}
console.info('Start polling data...')
this.pollData()
}

2
sapl/celery.py

@ -10,7 +10,7 @@ app.config_from_object('django.conf:settings', namespace='CELERY')
app.conf.beat_schedule = {
'get_cronometro_inst': {
'task': 'sapl.painel.tasks.get_cronometro',
'schedule': 10.0
'schedule': 1.0
}
}

16
sapl/painel/consumers.py

@ -2,14 +2,13 @@ import json
from channels.generic.websocket import WebsocketConsumer
class ChatConsumer(WebsocketConsumer):
class PainelConsumer(WebsocketConsumer):
def connect(self):
self.channel_layer.group_add('message', self.channel_name)
self.accept()
print('conectado ao ws')
def disconnect(self, close_code):
print('desconectado ao ws')
pass
async def disconnect(self, close_code):
await self.channel_layer.group_discard('message', self.channel_name)
def receive(self, text_data):
print('receive message')
@ -18,4 +17,9 @@ class ChatConsumer(WebsocketConsumer):
self.send(text_data=json.dumps({
'message': message
}))
}))
async def send(self, event):
new_data = event['text']
print(new_data)
await self.send(json.dumps(new_data))

4
sapl/painel/routing.py

@ -1,6 +1,6 @@
from django.urls import re_path
from django.urls import path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/painel/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
path('ws/painel/', consumers.PainelConsumer.as_asgi()),
]

29
sapl/painel/tasks.py

@ -4,16 +4,25 @@ import urllib
from celery import shared_task
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
channel_layer = get_channel_layer()
@shared_task
def get_cronometro():
url_dados = 'http://localhost:8000/painel/1272/dados'
# print(requests.get(url_dados).status_code)
#response = requests.get(url_dados)
response = urllib.request.urlopen(url_dados)
dados = json.loads(response.read())
#cronometro = response['sessao_plenaria']['cronometro_discurso']
print(dados)
print(response)
print(response.encoding)
return response
url_dados = 'http://localhost:8000/painel/786/dados'
login_data = {'username': 'sapl', 'password': 'sapl'}
with requests.Session() as session:
session.get('http://localhost:8000/login/')
csrftoken = session.cookies['csrftoken']
login_data['csrfmiddlewaretoken'] = csrftoken
post = session.post('http://localhost:8000/login/', data=login_data)
if post.ok: print('conexao realizada com sucesso')
r = session.get('http://localhost:8000/painel/786/dados')
json_data = r.json()
print(json_data)
async_to_sync(channel_layer.group_send)('message', {'type':'send', 'text': json_data})

2
sapl/painel/urls.py

@ -26,5 +26,5 @@ urlpatterns = [
url(r'^voto-individual/$', votante_view,
name='voto_individual'),
path(r'<str:room_name>/', room, name='room'),
path(r'chat/', room, name='room'),
]

4
sapl/painel/views.py

@ -645,7 +645,7 @@ def get_dados_painel(request, pk):
return response_nenhuma_materia(get_presentes(pk, response, None))
def room(request, room_name):
def room(request):
return render(request, 'painel/room.html', {
'room_name': room_name
'room_name': 'chat'
})

12
sapl/settings.py

@ -129,15 +129,15 @@ HAYSTACK_CONNECTIONS = {
CHANNEL_LAYERS = {
'default': {
### Method 1: Via local Redis
# 'BACKEND': 'channels_redis.core.RedisChannelLayer',
# 'CONFIG': {
# "hosts": [('127.0.0.1', 6379)],
# },
## Method 1: Via local Redis
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
### Method 3: Via In-memory channel layer
## Using this method.
"BACKEND": "channels.layers.InMemoryChannelLayer"
# "BACKEND": "channels.layers.InMemoryChannelLayer"
}
}

Loading…
Cancel
Save