Is there any way to send messages in real time without using websockets?

For example: in a certain part of the view after some event has completed: send_message(text)

def send_message(text):
  data = {'message': f'{text}'}
    return JsonResponse(data)

class RegisterView(CreateView):
      ...
  def form_valid(self, form):
    ...
    user.save()
    send_message("registered successfully")
    ... # view keeps running 

I tried to configure an ajax script to receive responses in real time but I couldn’t, if anyone knows how to do it please tell me. I managed to send messages in real time with StreamingHttpResponse, the big problem is that this has to be done in a view dedicated to streaming and I can’t call this streaming view in a normal view to pass personalized messages at the right time. I’m reluctant to use websockets because I think it will weigh down the server too much.

The direct answer to your question is “No”.

Fundamentally, the HTTP protocol is a “pull” protocol - all requests for data transfer must be initiated by the browser. The server cannot “push” data out.

Before websockets became practical, techniques such as long- and short-polling were used to have the browser periodically request updates. This may still be an option, depending upon the number of browsers you’re looking at supporting and what precisely you mean by “real time”.

Side note, websockets put a much lower load on a server than a StreamingHttpResponse, and less load than polling on short intervals. In all of these cases, they all work by opening a TCP socket that the server needs to handle.

1 Like