But i have the following error in consumer.py in "def mensaje": raise ValueError("No handler for message type %s" % message["type"]):
Mi code in consumers.py:
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from .tasks import PruebaCelery
class Consumer(AsyncJsonWebsocketConsumer):
async def connect(self):
print(self.channel_name)
await self.accept()
print("[BACK]:Cliente conectado")
async def disconnect(self, close_code):
return None
async def receive_json(self, contenido):
try:
if True:
print("[BACK]:Datos recividos",contenido)
await self.mensaje(contenido)
except:
pass
async def mensaje(self, contenido):
print("[BACK]:Si se cumple la condicion se envia mensaje")
print(contenido["Clave_Tipo_Filtro"])
TipoFiltro = contenido["Clave_Tipo_Filtro"]
if TipoFiltro == "Filtro_Paso_Bajo":
print("dentro")
mensaje = PruebaCelery.delay(self.channel_name)
print("Here")
print ("hola %s" %str(mensaje["text"]))
print("Out")
print ("Task ID: %s" %mensaje)
await self.send("Task ID: %s" %str(mensaje))
await self.send("se ha ejecutado celery")
else:
print("no entra")
return NoneMi code in tasks.py:
#De celery
from Filtros.celery import app
import json
from channels.layers import get_channel_layer
from asgiref.sync import AsyncToSync
@app.task
def PruebaCelery(channel_name):
# responder al cliente
channel_layer = get_channel_layer()
AsyncToSync(channel_layer.send)(
channel_name,
{"type": "Test",
"text": json.dumps("Hi im celery"),
})<script type="text/javascript">
//Envio de la conexion del front al back.
function onOpen(evt) {
console.log("[FRONT]:El websocket ha sido conectado");
websocket.send(JSON.stringify({data: "[FRONT]:El websocket esta conectado...ahora estas conectado con el front"}));
}
//Recepcion datos del back al front
function onMessage(evt) {
console.log("[FRONT]:Mensaje recibido del back al front:" + evt.data);
}
//Conexion del websocket
function setupWebSocket() {
prefix = "ws";
websocket = new WebSocket(prefix + "://" + location.host + "/Crear_FPB/");
websocket.onopen = function(evt) { onOpen(evt); };
websocket.onmessage = function(evt) { onMessage(evt); };
}
//Envio de los datos del formulario del front al back.
function runButton() {
var variables_FPBajo = {
Clave_Tipo_Filtro: "Filtro_Paso_Bajo",
Clave_Ap_db: $("#Valor_Ap_db").val(),
Clave_Medida_Ap_db: $("#Medida_Ap_db").val(),
Clave_As_db: $("#Valor_As_db").val(),
Clave_Fp_Hz: $("#Valor_Fp_Hz").val()
};
websocket.send(JSON.stringify(variables_FPBajo));
}
window.addEventListener("load", setupWebSocket);
Mi code in routing.py:
from django.urls import path
#from channels.http import AsgiHandlerfrom channels.routing import ProtocolTypeRouter, URLRouterfrom channels.auth import AuthMiddlewareStack
from F_Paso_Bajo.consumers import Consumer
application = ProtocolTypeRouter({
# Channels will do this for you automatically. It's included here as an example. # "http": AsgiHandler,
# Route all WebSocket requests to our custom chat handler. # We actually don't need the URLRouter here, but we've put it in for # illustration. Also note the inclusion of the AuthMiddlewareStack to # add users and sessions - see http://channels.readthedocs.io/en/latest/topics/authentication.html "websocket": AuthMiddlewareStack( URLRouter([ # URLRouter just takes standard Django path() or url() entries. # URL del javascript path("Crear_FPB/", Consumer), ]), ),
})