HI,
I am using SyncConsumer with HTTP protocol (not WebSocket ) for background work by referring this document Worker and Background Tasks — Channels 4.0.0 documentation. I have seen there are connect, disconnect & receive method when you use WebSocket protocol, but i am not getting how can i write these method using HTTP protocol. As of now In SyncConsumer class there is only dispatch and send method.
Also, i am trying to use channels.exceptions import StopConsumer, how can i use them and test it through code whether its working or not.
I am calling consumer from outside,
from random import randint
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from django.http import HttpResponse
---------------view.py------------------------
channel_layer = get_channel_layer()
def start_task_a(request):
id = randint(0,1000)
async_to_sync(channel_layer.send)(‘background-tasks’, {‘type’: ‘task.a’, ‘id’: id})
return HttpResponse(‘task_a message sent with id={}’.format(id), content_type=‘text/plain’)
def start_task_b(request, wait):
async_to_sync(channel_layer.send)(‘background-tasks’, {‘type’: ‘task.b’, ‘wait’: wait})
return HttpResponse(‘task_b message sent with wait={}’.format(wait), content_type=‘text/plain’)
---------------consumer.py------------------------
from time import sleep
from channels.consumer import SyncConsumer
from channels.exceptions import StopConsumer
class BackgroundTaskConsumer(SyncConsumer):
def task_a(self, message):
print("Consusmer A Connected")
sleep(5)
def task_b(self, message):
print("Consusmer B Connected")
sleep(message['wait'])
Any help greatly appreciated !!