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. 14
      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', el: '#app-painel',
data () { data () {
return { return {
message: 'Hello VueJUS', // TODO: remove when porting to VueJS is done message: null, // TODO: remove when porting to VueJS is done
polling: null, polling: null,
painel_aberto: true, painel_aberto: true,
sessao_plenaria: '', sessao_plenaria: '',
@ -45,6 +45,7 @@ const v = new Vue({ // eslint-disable-line
resultado_votacao_css: '', resultado_votacao_css: '',
tipo_resultado: '', tipo_resultado: '',
tipo_votacao: '', tipo_votacao: '',
teste: null,
running: 0 running: 0
} }
}, },
@ -251,7 +252,7 @@ const v = new Vue({ // eslint-disable-line
this.fetchData() this.fetchData()
this.polling = setInterval(() => { this.polling = setInterval(() => {
console.info('Fetching data from backend') // console.info('Fetching data from backend')
this.fetchData() this.fetchData()
}, 100) }, 100)
} }
@ -261,6 +262,22 @@ const v = new Vue({ // eslint-disable-line
clearInterval(this.polling) clearInterval(this.polling)
}, },
created () { 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...') console.info('Start polling data...')
this.pollData() this.pollData()
} }

2
sapl/celery.py

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

14
sapl/painel/consumers.py

@ -2,14 +2,13 @@ import json
from channels.generic.websocket import WebsocketConsumer from channels.generic.websocket import WebsocketConsumer
class ChatConsumer(WebsocketConsumer): class PainelConsumer(WebsocketConsumer):
def connect(self): def connect(self):
self.channel_layer.group_add('message', self.channel_name)
self.accept() self.accept()
print('conectado ao ws')
def disconnect(self, close_code): async def disconnect(self, close_code):
print('desconectado ao ws') await self.channel_layer.group_discard('message', self.channel_name)
pass
def receive(self, text_data): def receive(self, text_data):
print('receive message') print('receive message')
@ -19,3 +18,8 @@ class ChatConsumer(WebsocketConsumer):
self.send(text_data=json.dumps({ self.send(text_data=json.dumps({
'message': message '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 from . import consumers
websocket_urlpatterns = [ 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 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 @shared_task
def get_cronometro(): def get_cronometro():
url_dados = 'http://localhost:8000/painel/1272/dados' url_dados = 'http://localhost:8000/painel/786/dados'
# print(requests.get(url_dados).status_code)
#response = requests.get(url_dados)
response = urllib.request.urlopen(url_dados) login_data = {'username': 'sapl', 'password': 'sapl'}
dados = json.loads(response.read()) with requests.Session() as session:
#cronometro = response['sessao_plenaria']['cronometro_discurso'] session.get('http://localhost:8000/login/')
print(dados) csrftoken = session.cookies['csrftoken']
print(response) login_data['csrfmiddlewaretoken'] = csrftoken
print(response.encoding) post = session.post('http://localhost:8000/login/', data=login_data)
return response 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, url(r'^voto-individual/$', votante_view,
name='voto_individual'), 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)) return response_nenhuma_materia(get_presentes(pk, response, None))
def room(request, room_name): def room(request):
return render(request, 'painel/room.html', { 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 = { CHANNEL_LAYERS = {
'default': { 'default': {
### Method 1: Via local Redis ## Method 1: Via local Redis
# 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'BACKEND': 'channels_redis.core.RedisChannelLayer',
# 'CONFIG': { 'CONFIG': {
# "hosts": [('127.0.0.1', 6379)], "hosts": [('127.0.0.1', 6379)],
# }, },
### Method 3: Via In-memory channel layer ### Method 3: Via In-memory channel layer
## Using this method. ## Using this method.
"BACKEND": "channels.layers.InMemoryChannelLayer" # "BACKEND": "channels.layers.InMemoryChannelLayer"
} }
} }

Loading…
Cancel
Save