How to Use Socket.io to send Messages from views.py ?

OK, so when i do it from outside the views.py it works perfectly and it console.logs in my browser running django.

my socketio_server.py file in the project folder

import socketio
import eventlet.wsgi

# create a Socket.IO server
sio = socketio.Server(cors_allowed_origins='*')

# wrap with a WSGI application
app = socketio.WSGIApp(sio)

@sio.event
def connect(sid, environ):
    print('Client connected:', sid)


# start the server and listen for connections
if __name__ == '__main__':
    eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 8080)), app)

I then run this file using python3 socketio_server.py in the terminal

 python3 socketio_server.py
(325591) wsgi starting up on http://0.0.0.0:8080

my JS file

const socket = io('http://localhost:8080');

socket.on('connect', () => {
    console.log('Socket connected');
  });


// # The below message needs to come from django views, but i get no such message in the console output

socket.on('django', (data) => {
  console.log(data);
});

so in the above js file i get the console.log of socket.on (connect)

but not the below message which comes from the views

my views.py file

from practice.socketio_server import sio

# Create your views here.

def socket_testing(request):

    sio.emit("django","THIS MESSAGE IS FROM DJANGO VIEWS")
    print("I GOT THE MESSAGE")
    return render(request, 'testing/socket_testing.html')

i run my python3 manage.py runserver 0.0.0.0:9000
and the python3 socketio_server.py on port 8080

so maybe the port difference is the issue ? Please help thanks :slight_smile:

No, the issue is that you’re trying to handle websockets within a Django view.

You can’t do that.

Handling websockets is something that must be done outside the regular Django environment. That’s where things like Channels comes into play.

Also see Send Notifications in real time using Python Engineio

actully there was a module/library for django called django_socketio, but its been outdated since last 4 yrs :frowning:

Use django channels?

they are a bit complicated, thats why was checking socket.io out,

should i introduce node.js to my project ? so socket.io, node.js and django can work together. or is it too much ?

Which does not do what you think it did.

It still required an external process to run to be the websocket endpoint - it did not allow for a Django view to handle a websocket.

And you thought Channels was complex?

The question is what degree of integration that you’re looking for. If you want your websocket handler to have access to your models (which includes the ability to share authentication and permissions), then Channels is by far the easiest way to handle that.

If the websocket has no need for access to any other part of your Django environment, then any websocket interface would be sufficient.

2 Likes

Well, using two servers is obviously going to complicate stuff. Also, depends on what you are trying to achieve/build.
I would suggest that you try to understand the channels documentation.
I tried it myself, long time back though.
You can refer my repos if you would like to:

1 Like

I’ll also point out that the HTMX websocket extension works extremely well with Channels. (I’m using it exclusively on the client side for websocket transfers.)

Hi so basically i use ajax for my like button and also follow button (and as soon someone follows a user) they get a notification.

But the problem is ajax sends request in every page looking for the notification and i can ofcourse delay it… but what I really want is the user to get it real time notification.
So i guess channels is my best bet.

Hi,so basically i use ajax for my like button and also follow button (and as soon someone follows a user) they get a notification.

But the problem is ajax sends request in every page looking for the notification and i can ofcourse delay it… but what I really want is the user to get a real time notification.
So i guess channels is my best bet.

Maybe, maybe not.

“Best” is really a relative term here. There’s no one “right” answer.

You need to determine whether the benefits of supporting a full websocket environment is worth the effort, or if a polling solution would really be adequate for this purpose.

Seriously, how critical is it that a person receive this notification in 1 second instead of 3? Or 3 seconds instead of 30?

What percentage of the time is the person even going to have that page open to receive that notification when another person clicks “like” or “follow”?

Are you better equipped to handle long- or short- polling instead of websockets?

It’s one thing to talk about this in the abstract, it’s another to architect your systems based upon real requirements instead of perceived requirements. And those are questions only you can answer. (We’re not in a position to know or understand the underlying requirements and the implications of the decisions resulting from that.)

1 Like

Actully i have read that maybe as my users visits increase on the site… ajax is not good for long term usage correct ? Or i maybe wrong

My site is simple… the user can only like an image… follow another user and share images to social media… that’s it.

Again, there’s no “one” answer to that. It really does depend upon a lot of things - number and level of activity of the users being two of the factors involved.

You also need to look at how you’re going to deploy this and what constraints that environment may impose.

You also need to evaluate on-going monitoring and maintenance requirements. (No deployment environment is going to be “deploy and forget about it”.)

These are all “big picture” issues that may (should?) affect some of the architectural decisions being made. They shouldn’t (can’t?) be effectively made in the absence of the overall environment in which your system is going to run.

1 Like

Hi. You are absolutely right. May i ask you what were the biggest projects or apps you had to scale in django keeping user activity in mind as it grows. And the biggest hurdles in the way thanks.

I did deploy my app to heroku few months back to test and that’s it. But have added way more functionality to my site since then.

Thanks

I work in an environment with a small-but-consistent user base. (95+% of my work in internal to the company or a very constrained set of outside users.)

The largest such project I work on has about 5000 regular users in one of the deployments.

My largest Channels-assisted app only services about 50 websockets (at most), probably no more than 10 at any given time.

In neither of these cases have I needed to make any specific adaptations for scale. (We also self-host, so I have complete control over the server.)

Actually, I’m going to take that back a little. We do use a custom configuration for our PostgreSQL instances for the larger deployments. We increase the memory allocation to effectively ensure that the entire database and indexes (4GBish) are completely memory resident. It’s perhaps overkill, but when our smallest standard VM is 8 GB, the memory should probably be put to good use somewhere.

2 Likes