I
I
Ilya Ryabykin2019-01-06 18:11:56
Django
Ilya Ryabykin, 2019-01-06 18:11:56

How is the base_send method defined in the channels module?

Hello.
I'm trying to figure out how the channels library for Django works.
I can't figure out how the base_send method is formed for the *Consumer classes (AsyncConsumer, SyncConsumer, etc.).
All *Consumer classes inherit from AsyncConsumer and have a send method that calls self.base_send:

def send(self, message):
        """
        Overrideable/callable-by-subclasses send method.
        """
        self.base_send(message)

base_send in AsyncConsumer is set in only one place - the __call_ method in the following form:
class AsyncConsumer:
    """
    Base consumer class. Implements the ASGI application spec, and adds on
    channel layer management and routing of events to named methods based
    on their type.
    """
    async def __call__(self, receive, send):
        """
        Dispatches incoming messages to type-based handlers asynchronously.
        """
        ...
        # Store send function
        if self._sync:
            self.base_send = async_to_sync(send)
        else:
            self.base_send = send
       ...

But looking at the running code, nowhere after initializing an instance of the *Consumer class, the __call__ method is called with these "receive, send" magic arguments.
I don’t even want to do what I got into this jungle because of, but I want to know how it works .
Good people, give me some help, lack of knowledge makes itself felt)
Classes AsyncConsumer, SyncConsumer - here
Work happens directly with the WebsocketConsumer(SyncConsumer) class, which is here
Working code:
class CommandsConsumer(WebsocketConsumer):

    def connect(self):
        # create connection to server once
        self.accept()

    def disconnect(self, close_code='0'):
        print('Web-socket connection closed with code {}'.format(close_code))

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        self.send(text_data=json.dumps({
            'message': str(text_data_json['message'])
        }))

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question