Help with Channels 2.x and Celery 4.x

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

Help with Channels 2.x and Celery 4.x

Sergio Lopez
Hi!! I need a basic example of a program with channels 2.x (Django 2.x) that when it fulfills a condition, it calls a task celery 4.x and updates its status in a message in the html. (for example https://vincenttide.com/blog/1/django-channels-and-celery-example/)

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 None

Mi 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"),
                 })

Mi code in htmlhow could I print "hi im celery" in the html?
<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 AsgiHandler
from channels.routing import ProtocolTypeRouter, URLRouter
from 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),
        ]),
    ),

})




--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
To post to this group, send email to [hidden email].
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e9f5278c-3386-4c45-ae00-be753e6745f2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.