How to use connect and disconnect, receive method in SyncConsumer using HTTP protocol


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
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’)

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")

 def task_b(self, message):
    print("Consusmer B Connected")

Any help greatly appreciated !!

You don’t.

This appears to be an X-Y Problem

What is your ultimate objective here? What are you really trying to accomplish?

A background worker listens to a “channel” and responds to messages placed on that channel. It does not directly respond to external requests.

Hi Kent, Sorry for lengthy question, in short problem is I am trying to use websocket_connect, websocket_receive and websocket_disconnect method for HTTP protocal. Refer this link Consumers — Channels 4.0.0 documentation for SyncConsumer these methods are used for Websocket protocal . I want to know do we have same kind of method of HTTP protocal.

Also, what is use of StopConsumer can i use it background job. If yes how can test it is it working?

Again, you don’t. It doesn’t make sense to even talk about this in those terms.

You need to take a step back and look at this from a “higher level” perspective. What are you trying to accomplish by doing this? What requirements are being addressed by thinking that this might be a solution?

Thanks Ken. I will rethink on this. Again thanks for your time and response.