I have a frontend consumer that handles HTTP requests (webhooks)
from django.views.decorators.csrf import csrf_exempt
from channels.generic.http import AsyncHttpConsumer
from django.http import JsonResponse
import json
import myapp.models
import redis
@csrf_exempt
class frontEndConsumer(AsyncHttpConsumer):
async def http_request(self, request):
await self.channel_layer.group_add("link", self.channel_name)
await self.channel_layer.group_send("link",
{
"type": "websocket.reg",
"where": "webhook",
"message": "test message",
})
#channel layer functions
async def webhook_reg(self, event):
print("WH: message from " + event["where"] + ": " + event["message"]
# make response
fulfillmentText = "device connected"
fulfillmentText = {'fulfillmentText': fulfillmentText}
fulfillmentText = json.dumps(fulfillmentText).encode('utf-8')
await self.send_response(200, fulfillmentText,
headers=[(b"Content-Type", b"text/plain"),])
and I have a backend consumer that handles websocket connections.
from channels.generic.websocket import AsyncJsonWebsocketConsumer
import redis
import myapp.models
account = redis.Redis(db=0)
class backEndConsumer(AsyncJsonWebsocketConsumer):
async def websocket_connect(self, type):
await self.channel_layer.group_add("link", self.channel_name)
print("channel name: " + self.channel_name)
await self.accept()
#channel layer functions
async def websocket_reg(self, event):
print("WS: message from " + event["where"] + ": " + event["message"])
await self.channel_layer.group_send("link",
{
"type": "webhook.reg",
"where": "websocket",
"message": "msg from websocket",
})
await self.send(event["message"])
I start them in procfile with:
web: daphne APbackend.asgi:application --port $PORT --bind 0.0.0.0
I am using django channels to have the front and back talk to each other. In my code, I’m trying to get both sides to send messages to each other.
- I would establish websocket connection
- have webhook send a http request to my front end.
- front end would send a message to the backend (via channel messaging)
- backend would send a message to the frontend.
- front end message would finish the http request.
But this doesn’t work, step 4, with the message going back to the front end saying the handler is missing. Why is that?
2
Answers
I was able to get this to work using either two group names or two channel names. Also knowing http_reponse would end the http_request context helped me debug why I wasn't able to get message back to dialogflow.
Thanks!
You are using the same group to talk in both directions this means when you send
webhook.reg
from the backend it will end up trying to call the functionwebhook_reg
on eachbackEndConsumer
instance but there is no such method there.You should create 2 groups.
backend_to_frontend
frontend_to_backend
frontend
shouldgroup_add
thebackend_to_frontend
backend
shouldgroup_add
thefrontend_to_backend
&
backend
you shouldgroup_send
to thebackend_to_frontend
frontend
you shouldgroup_send
to thefrontend_to_backend