Skip to main content

Websockets in Django

"WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C."
WebSockets are used for streaming messages. To implement real-time notification we need to stream messages from the server to the client without a refresh or making an HTTP request from the client. Hence websockets.

We will be implementing sockets in Django using Django Channels. Channels is a project that takes Django and extends its abilities beyond HTTP - to handle WebSockets, chat protocols, IoT protocols, and more.  But WSGI server does not support websockets(present gateway interface used by graphspace). We will be using Daphne, a server specially designed for channels. It's pretty easy to deploy channels on Daphne. For websockets we will be using ASGI as the gateway interface and Daphne as the server. Daphne will be able to handle both HTTP and websocket requests. Deploying channels on Daphne is fairly easy (Tutorial). In the tutorial, you will find this, "ASGI and its canonical interface server Daphne are both relatively new, and so you may not wish to run all your traffic through it yet (or you may be using specialized features of your existing WSGI server)". As stated its not recommended to use Daphne for all the traffic.
There are 2 solutions: 
  1. We can ignore the warning and go ahead with Daphne. This is the easier solution and probably will work for small number of users.
  2. We can use Apache for HTTP requests and Daphne for websockets
Solution 2 should be implemented to support a large number of users on GraphSpace at the same time. For Daphne, Apache acts like a reverse proxy, redirecting all the websocket requests to Daphne server which is running on a different port. To setup WSGI server for GraphSpace follow the steps here. Now we need to setup Apache as a reverse proxy, follow these steps:
  1. Run the following terminal command: 
    • a2enmod rewrite 
    • a2enmod proxy 
    • a2enmod proxy_wstunnel
  2. Inside the 000-default.conf, copy and paste following lines inside <VirtualHost *:80> </VirtualHost>
    RewriteEngine on
    RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR]
    RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC]
    RewriteRule .* ws://127.0.0.1:9099%{REQUEST_URI} [P,QSA,L]
    Update port and host according to Daphne port.
    The above commands checks for "UPGRADE" attribute in a the request from a client and reroutes it to Daphne if it is set to websocket.
Now you have a WSGI server running in Apache and a Daphne server for websockets. Enjoy!

"Why use Django-channels?"

1) First of all it is very easy to understand and use. A simple tutorial is here including building a real-time chat service using channels
2) Asynchronous in nature and but still we can write synchronous code. Example operations like monkey-patching can be done without issues.
3) In one big package, one of the fantastic features is Group through which we can send a message to a number of channels by adding them to a group (very useful in sending same comment to multiple clients at the same time).
4) Each socket or connection to your overall application is handled by a application instance inside one of these servers. They get called and can send data back to the client directly. However, as you build more complex application systems you start needing to communicate between different application instances - for example, if you are building a chat-room, when one application instance receives an incoming message, it needs to distribute it out to any other instances that represent people in the chat-room. You can do this by polling a database, but Channels introduces the idea of a channel layer, a low-level abstraction around a set of transports that allow you to send information between different processes.
5) However it has some limitations such as channel layer choices are limited(IPC, Redis).

 "What is ASGI and WSGI? What is the difference?"
When we say WSGI (Web Server Gateway Interface) or ASGI (Asynch-
ronous Server Gateway Interface), these are specifications (explained in detail here and here). The difference between the 2 is WSGI was desig-
ned for HTTP request-response type cycle, whereas ASGI is much boarder. (Read more)

 "Apache as reverse proxy". What is reverse proxy?
This stackoverflow answer explains it the best.

Comments

Popular posts from this blog

Project Introduction

Comment System for GraphSpace Organization : National Resource for Network Biology (NRNB) GraphSpace is an user-friendly web-based platform that collaborating research groups can utilize for storage, interaction, and network sharing. A GraphSpace user can import graphs created in Cytoscape , upload them through a REST API, interact with them by customizing and saving layouts, share them within and between groups of collaborators, search for different graphs, and organize them using tags. These functions are enabled through GraphSpace’s comprehensive REST API, which allows users to communicate. Several research groups and people using GraphSpace would like not only to visualize the graph but also discuss about different nodes, edges and subgraphs present in the graph. Effective discussion about the graphs can be promoted with the help of comments. The aim of this project is to implement a real-time system that will allow users to comment on graphs and discuss ideas with each...