Browse Source

Conexão ws com Vue usando o celery

Websocket_painel
Gustavo274 3 years ago
parent
commit
559b6ce690
  1. 20
      frontend/src/__apps/painel/main.js
  2. 6
      sapl/celery.py
  3. 16
      sapl/painel/consumers.py
  4. 23
      sapl/painel/tasks.py
  5. 2
      sapl/painel/views.py

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

@ -242,24 +242,8 @@ const v = new Vue({ // eslint-disable-line
this.started = setInterval(() => { this.started = setInterval(() => {
this.clockRunning(crono) this.clockRunning(crono)
}, 100) }, 100)
},
call_data: function call_data () {
socket.send('Calling Data...')
},
pollData () {
/* this.fetchData() */
this.polling = setInterval(() => {
// console.info('Fetching data from backend')
this.call_data()
this.fetchData()
/* console.log(this.teste) */
}, 1000)
} }
}, },
beforeDestroy () {
console.info('Destroying polling.')
clearInterval(this.polling)
},
created () { created () {
socket.onopen = function (e) { socket.onopen = function (e) {
console.log('Connection established') console.log('Connection established')
@ -269,14 +253,12 @@ const v = new Vue({ // eslint-disable-line
socket.onmessage = function (e) { socket.onmessage = function (e) {
_this.teste = JSON.parse(e.data) _this.teste = JSON.parse(e.data)
_this.fetchData()
console.log('Data Received...') console.log('Data Received...')
} }
socket.onclose = function (e) { socket.onclose = function (e) {
console.error('Ws fechou!') console.error('Ws fechou!')
} }
console.info('Start polling data...')
this.pollData()
} }
}) })

6
sapl/celery.py

@ -8,9 +8,9 @@ app = Celery('sapl')
app.config_from_object('django.conf:settings', namespace='CELERY') app.config_from_object('django.conf:settings', namespace='CELERY')
app.conf.beat_schedule = { app.conf.beat_schedule = {
'get_cronometro_inst': { 'get_dados_inst': {
'task': 'sapl.painel.tasks.get_cronometro', 'task': 'sapl.painel.tasks.get_dados_painel_celery',
'schedule': 1.0 'schedule': 0.2
} }
} }

16
sapl/painel/consumers.py

@ -8,18 +8,14 @@ from sapl.painel import views
class PainelConsumer(AsyncJsonWebsocketConsumer): class PainelConsumer(AsyncJsonWebsocketConsumer):
async def connect (self): async def connect (self):
print('Conectado') print('Conectado')
await self.channel_layer.group_add('painel', self.channel_name)
await self.accept() await self.accept()
async def disconnect(self, close_code): async def disconnect(self, code):
print('Desconectado:', close_code) await self.channel_layer.group_discard('painel', self.channel_name)
pass
async def receive(self, text_data):
await self.send_data(786) async def send_data(self, event):
new_data = event['message']
async def send_data(self, id): await self.send(json.dumps(new_data))
response = views.get_dados_painel(id)
await self.send_json(response)

23
sapl/painel/tasks.py

@ -1,27 +1,14 @@
import json
import requests
import urllib
from celery import shared_task from celery import shared_task
from urllib import request
from channels.layers import get_channel_layer from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync from asgiref.sync import async_to_sync
from sapl.painel import views
channel_layer = get_channel_layer() channel_layer = get_channel_layer()
@shared_task @shared_task
def get_cronometro(): def get_dados_painel_celery():
url_dados = 'http://localhost:8000/painel/786/dados' json_data = views.get_dados_painel(786)
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()
async_to_sync(channel_layer.group_send)('painel', {'type':'send_data', 'message': json_data}) async_to_sync(channel_layer.group_send)('painel', {'type':'send_data', 'message': json_data})

2
sapl/painel/views.py

@ -348,7 +348,7 @@ def cronometro_painel(request):
return HttpResponse({}) return HttpResponse({})
def get_cronometro_status(name): def get_cronometro_status(request, name):
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
username = request.user.username username = request.user.username
try: try:

Loading…
Cancel
Save