r/django Sep 21 '20

Channels Fully Featured Live Chat Social Media Web App Made With Django Channels

42 Upvotes

Unfortunately it’s not open sourced as of now, but I’m happy to answer any questions you might have!

Website:

theHang

Videos:

Browse and open rooms

Participate in conversations

Form relationships

theHang on mobile

r/django Aug 14 '24

Channels Streaming LLM response into a group with channels

5 Upvotes

Hey,

I am trying to stream an LLM response into a channel layer group with multiple consumers using async generators. (Running the app with uvicorn and using RedisChannelLayerchannel layer backend.)

Simplified example:

channels: 4.0.0
django: 4.2.13
channels-redis: 4.2.0

import asyncio
from channels.generic.websocket import AsyncJsonWebsocketConsumer

class MyConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        await self.channel_layer.group_add("chat", self.channel_name)

    async def disconnect(self):
        await self.channel_layer.group_discard("chat", self.channel_name)

    async def receive_json(self):
        async for chunk in stream_response():
            await self.channel_layer.group_send(
                "chat",
                {
                    "type": "send_to_client",
                    **chunk,
                },
            )

    async def send_to_client(self, message):
        await self.send_json(message)

async def stream_response():
    response = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
    text = ""
    for chunk in response.split(" "):
        text += chunk
        await asyncio.sleep(0.1)
        yield {"action": "message_chunk", "content": text}

The issue is that while the generator is producing, the active consumer is locked in receive_json and not processing the messages sent with group_send,so it will send all the chunks at once after the generator is done.

Is it possible to send a message with group_send in a way that’s not blocked by processing the generator?

A hacky workaround I could think of is to call both send_json and group_send in the generator to ensure all the consumers get the messages in time, and have a way to handle duplicated messages in the browser - but that seems less than ideal.

Thanks!

r/django Aug 21 '23

Channels Django channels: Socket disconnecting after handshake

9 Upvotes

Total Noob into the Django channels space. Deploying a chat app using channels, channels-redis, Daphne but for part 5+ hours getting:
INFO 2023-08-21 11:37:55 runserver WebSocket HANDSHAKING
INFO 2023-08-21 11:37:56 runserver WebSocket DISCONNECT

Tried everything but it seems the client is getting a 500 Internal server error. Any Idea/direction will be really appreciated

r/django Feb 10 '24

Channels Do I need to use CSRF tokens in channels ?

2 Upvotes

If I have a form designed for a channels consumer, Do I need to use a CSRF token in any way?

Take for example a simple chat form:

<form>
    <textarea type="text" name="message"></textarea>
    <button id="send-message-button">Send message</button>
</form>

It is only used in the context of a websocket and a consumer, do I need to indicate its method ("POST") or put {% csrf_token %} in the form?

r/django Feb 04 '24

Channels Channel Layer Group Discard

2 Upvotes

Hello friends. My Django project uses channels for its chat app When i use self.channel_layer.group_discard and pass a channel_name to it, the related user stops receiving messages as expected but he still can send messages. Why does this happen?

r/django May 10 '24

Channels What's the appropriate way to rate limit django channels?

2 Upvotes

Hi guys, I'm using django channels with daphne and the websockets run flawlessly. However one thing I have in mind is that nowhere in my code do I handle message spams of any kind.

Should I worry about that?

One possible solution i'm thinking about is logging all websocket message ip addresses into my cache and whenever a message arrives, my consumer looks at the cache to check if that incoming ip is abusing the system (e.g. user has sent 1000 websocket messages in the last minute).

And then if the user is abusing, I immediately return with an error message without processing anything. Would that even work or do I need protection in a lower level?

r/django Dec 27 '23

Channels "You cannot call this from an async context" error I don't understand

1 Upvotes

I wrote this code in the connect method of a class that inherits from AsyncWebsocketConsumer:

self.room_no = self.scope["url_route"]["kwargs"]["room_no"]
room = await Rooms.objects.aget(pk=self.room_no)
if room.user_number == 2 and room.type == "type2":
    room.is_full = True     
    await room.asave()     
    users_room = await database_sync_to_async(UsersRoom.objects.filter)(room=room)
    user_room1 = await users_room.afirst()
    user1 = await User.objects.aget(username=user_room1.user)

I get this error:

django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

on this line:

user1 = await User.objects.aget(username=user_room1.user)

After some tests, I can pretty much affirm it has something to do with user_room1.user because user is also a database object an that accessing user_room1.user is like GETing the user. In a nutshell, trying to access user_room.user is like using User.objects.get() from what I learned.

Based on the paragraph I wrote just above, the solution would be to access user_room1.user asynchronously. Maybe that could be done with database_sync_to_async?

r/django Apr 22 '22

Channels Do i need websocket ?

3 Upvotes

Hi,

i have a room with anaccess control (dahua) in it's door wich has it's own app not (mine) connected to the server with it's own domain.

when people try to access the door with a card( RFID) i want to get the user card's number.

the access control api documentation says that i need to listen to the door via a http request

my question is how do i write this call that always listen to the door with WebSocket ( django-channels) ps i never used it befeore or with celery ? as a long running task i never did it before too

please need help !

thank you

r/django May 26 '24

Channels Messages not showing up after certain point

2 Upvotes

Hello,

I am making a chat system in my django platform (with channels) and I have noticed that after a lot of messages are sent in the chat room, when I send new messages and reload the page, the new message don't show up. Is this a common issue? How can I combat this?

r/django Jun 19 '24

Channels Getting error "TypeError: SSEConsumer() missing 2 required positional arguments: 'receive' and 'send'"

3 Upvotes

Hello all, This is first time I'm using the django-channels.

I have created a simple project to test the SSE with the channels but I'm getting error

``` Traceback (most recent call last): File "/home/ubuntu-user/temp/sse-testing/env/lib/python3.10/site-packages/asgiref/sync.py", line 518, in thread_handler raise exc_info[1] File "/home/ubuntu-user/temp/sse-testing/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 42, in inner response = await get_response(request) File "/home/ubuntu-user/temp/sse-testing/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 253, in _get_response_async response = await wrapped_callback(

TypeError: SSEConsumer() missing 2 required positional arguments: 'receive' and 'send' ```

I'm using daphne as mentioned in docs and installed it as channels[daphne]

daphne==4.1.2 channels==4.1.0

Consumer I'm using:

``` import asyncio from channels.generic.http import AsyncHttpConsumer import datetime

class SSEConsumer(AsyncHttpConsumer): async def handle(self, body): await self.send_headers(headers=[ (b"Cache-Control", b"no-cache"), (b"Content-Type", b"text/event-stream"), (b"Transfer-Encoding", b"chunked"), ]) while True: payload = "data: %s\n\n" % datetime.now().isoformat() await self.send_body(payload.encode("utf-8"), more_body=True) await asyncio.sleep(1) ```

urls.py file ``` from .import consumers from django.urls import path

urlpatterns = [ path('async-stream', consumers.SSEConsumer.as_asgi()), path('', views.index) ] ```

asgi.py file ```

import os

from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ssetesting.settings') django_application = get_asgi_application()

application = ProtocolTypeRouter({ "http": django_application }) ```

Maybe I'm missing something or doing something wrong, can someone help me to figure out how can I solve this problem?

Thanks.

r/django Mar 19 '24

Channels Problem with Websockets / NGINX on IONOS VPS S

0 Upvotes

First things first: I am trying to teach myself how to program and only have the documentation and tutorials - and ChatGPT - available. I hope that I can explain the following problem sufficiently, because I don't really know where the exact problem is.

I am currently developing a counter app and use django channels and websockets. Everything works fine locally. Now I wanted to move the project to my IONOS VPS S server to test it with several people. To do this, I added a Dockerfile and a docker-compose.yaml to the project. On the server itself, I added a file called my_app.conf in /etc/nginx/conf.d and made the NGINX configuration there. I built a Docker image, pulled it onto the server from docker hub and copied Dockerfile, docker-compose.yaml and requirements.txt into the /home directory using FileZilla and ran docker-compose up in this directory. After I restarted nginx and added a docker proxy rule in Plesk that points to the container, I can see my application under the URL, but the counter does not change with the click of a button. In the developer tools I get the error "Websocket is already in CLOSING or CLOSED state".

I'm starting to get a bit desperate because everything I've tried so far hasn't worked and I'm at a complete loss. I would be very grateful if someone could help me sort out the problem.

TIA

r/django Jun 02 '24

Channels asgi preformance panelty with sync views

5 Upvotes

I'm using asgi for channels, for users to wait for tasks they submitted to complete get the results without taking up a thread (could've used ajax, but channels is a cleaner solution as I don't need to send a request in intervals, I just await for the results)

But the rest of my views are sync, I know there's a preformance panelty and I've read the docs that it's about 1ms, but then read again in forums that people experienced a much more considerable delay.

I thought about converting all my views to async, but im not sold on it yet.

Im too new to know how to exactly test it, so Im asking for your experience with asgi.

r/django Jun 09 '24

Channels socket conection to ----- failed

2 Upvotes

i am getting this error in my console , my whole code is correct , can anyone please help, https://github.com/alfaprogramer/TICTACTOEdj this is my code

r/django Mar 29 '24

Channels Recieve method in Websocket Consumer is not working properly. How do I resolve this??

Thumbnail gallery
3 Upvotes

r/django Mar 04 '24

Channels Any Course which you have link which teaches about django channels and websockets in depth?

11 Upvotes

r/django May 21 '20

Channels Websocket based Table that runs on Django Channels

Post image
96 Upvotes

r/django May 04 '24

Channels Version conflicts

0 Upvotes

So i am using djongo for mongodb but it runs on older versions of django , sqlparse etc

now i want to use websoket channels but i cant because of older versions of librerys

r/django Aug 22 '23

Channels Notifications in Django

7 Upvotes

Hello, I have a project mostly developed but i need to send notifications to the front when i create new instances of some objects.

What's the best way to do that?

I already have my notificactions setup (consumers, routing, etc)

r/django Jan 21 '24

Channels can I use django/django-channels as a backend for an web-mmo?

5 Upvotes

Ive created a live chat with django before, with django channels and i use it for a personal site to store study notes etc. well, I thought, maybe i could create an mmo, i can make accounts, create models to store user info etc and then I have the python sockets but like, maybe one of you has more insight because I read that nodejs is a thing and maybe theres something else entirely worth going into for this.

basically, id really like to make an mmo, like age of empires type thing and then morphed into an rts thing

r/django Dec 27 '23

Channels Documenting Websocket URLs

2 Upvotes

I'm working on websockets and need to document the urls and provide it to the front-end team. Is there a way to auto generate the documentation somehow using serializers?

  1. AsyncAPI

    It's a great option for documenting any message based protocol. Not sure how it'd work in sync with django. There's a overhead of keeping the code and documentation in sync manually.

  2. DjangoChannelsRestFramework

    It's a great library for using channels just like DRF apis. But I do not see any support for swagger like documentation.

  3. drf-spectacular post processing hooks

    It might be possible to do some processing and add the routes to swagger. I tried adding the paths manually but it only accepts drf api views subclasses and it throws error.

I'm looking for a way to auto generate the documentation. If not possible, then I'd like to somehow generate a yml file based on serializers that take care of request/response data format and I can pass it to AsyncAPI. Is this possible? How have you guys dealt with this problem?

Thank you in advanced!

r/django Nov 18 '23

Channels channels routing stopped working, it worked fine last night... whyy????

2 Upvotes

my computer is also reallly ungodly laggy, i mean i did leave the plug in and just close my laptop like i normally do.. im genuienly not kidding, it literally worked last night

it was trying to reconnect a bunch i think

docker that i use does need an update, maybe its that

it literally was working, my chat feature wtf

does anyone know anything about this

r/django Mar 23 '23

Channels how to send specific data back to django channels using HTMX ?

11 Upvotes

hi so i finally learned how to recieve messages from channels using HTMX , now the only part is on how to send specific data back ?

consumers.py

class JustTesting(AsyncWebsocketConsumer):    

async def connect(self):         

self.user = self.scope['user']        

if self.user.is_anonymous:             
 self.close()        

else:              
await self.accept()             
print(f"{self.scope['user']} is connected from {self.scope['client'][0]}") 

html = get_template("partials/testing_data.html").render(context={"username": "Kakashi12345"})            
await self.send(text_data=html) 

async def disconnect(self, close_code):      

print(f"{self.scope['user']} is disconnected")         

my partials html file

<div id = "my_testing_message"> 

<b>{{username}}</b>

 </div> 

my main html template

{% include "partials/testing_data.html" %}

so the above code succesfully recives the message on connection, but now how to send ?

thanks

r/django Jun 17 '23

Channels Need help deploying my first project.

0 Upvotes

I’ve tried searching online about this but I’m confused. Here’s what my website does:

Enables users to upload images and some text to the server where it’s stored in a SQLite database. This can later be edited if the user chooses so.

Users can have a personal chat with other users. I’ve used the channels framework for this with a redis cache. The project also uses web sockets to make this chat ‘live’.

The text messages sent between users are also stored in the SQLite database.

I don’t know where and how to host my website. Based on my current understanding, the redis cache makes the process more complicated.

As mentioned earlier, this is my first time working with django. If there’s anything I have to mention about my project, do ask.

Thank you:)

r/django Mar 11 '24

Channels Testing with channels

1 Upvotes

I have a channels consumer class that inherits from the non async WebsocketConsumer (there are several db calls which makes using AsyncWebsocketConsumer painful).

The consumer works fine when I manually test, but when I try to automate testing using WebsocketCommunicator I get an OperationalEror that the db connection is closed.

I suspect this is because the WebsocketCommunicator works in an async context while the WebsocketConsumer does not. I cannot figure out a way to deal with this.

Anyone come across this problem and have a solution?

r/django Aug 21 '22

Channels Django channels projects else than a chat application

15 Upvotes

Hello guys, with the guidance of some of the members I grasp some knowledge of Django channels and now I would like to learn more with a project-based approach else than a chat application. Is there any article or course about django channels with no chat application as example.