[Solved]-How to use Channel instead of Group when using django channels?

5👍

Update:

channels version = 0.9

channels are 0.9 now so some changes are required for the client to receive the message from the server:

class Content:
    def __init__(self, reply_channel):
        self.reply_channel = reply_channel

    def send(self, json):
        self.reply_channel.send({
            'reply_channel': str(self.reply_channel),
            'text': dumps(json)
        })


def ws_message(message):
    content = Content(message.reply_channel)
    content.send({'hello': 'world'})

routing.py stays the same…


channels version < 0.9

Bah, it was a bit tricky but found it.

You have to use the message’s reply_channel property.
So this:

Group("news_providers_loading").send({'content': str(provider)})

turns into this:

Channel(message.reply_channel).send({'content': str(provider)})

What I got now is:

from channels import Channel
from .soup import ProviderParser, sort_articles_by_date
from .models import Provider
from django.template.loader import render_to_string
from json import dumps


class Content:
    def __init__(self, reply_channel):
        self.reply_channel = reply_channel

    def send(self, json):
        Channel(self.reply_channel).send({'content': dumps(json)})


def ws_message(message):
    providers = Provider.objects.all()
    content = Content(message.reply_channel)

    content.send({'providers_length': len(providers)})

    articles = []
    for provider in providers:

        content.send({'provider': str(provider)})

        parser = ProviderParser(provider)
        articles.extend(parser.parse_articles())

    sort_articles_by_date(articles)
    html = render_to_string('news_providers/article.html', {'articles': articles})

    content.send({'html': html})

routing.py

channel_routing = {
     "websocket.receive": "news_providers.consumers.ws_message",
}

Seems lighter, though you might want to keep connect, keepalive and disconnect methods (as simple foo methods) -not entirely sure about that-!

# connect, keepalive and disconnect
def ws_foo(message):
    pass

routing.py

channel_routing = {
    "websocket.connect": "news_providers.consumers.ws_foo",
    "websocket.keepalive": "news_providers.consumers.ws_foo",
    "websocket.receive": "news_providers.consumers.ws_message",
    "websocket.disconnect": "news_providers.consumers.ws_foo",
}

Leave a comment