IVI
IVI

Reputation: 2116

Django Channels or Tornado for a socket based connection

I am working on a project where I have a list of Petrol stations viewable via the Django Rest API showing Station data i.e. the availability of Fuel and Capacity.

I have also developed a microcontroller to detect fuel levels. Now the issue is that this data will be sent to my web backend every 10mins (could be reduced to 1min in future), updating the station model via the rest api. I'm not sure how to handle this. Would something like Django channels be useful in this case?

The server uses a mixture of C and Java to send data. I need it to be a scalable solution as there is a potential of many stations being created.

Upvotes: 0

Views: 2140

Answers (1)

IVI
IVI

Reputation: 2116

I will answer my own question. Websockets allow bi-directional communication mechanisms whether between a client browser and web server or a server to server communication.

There are many tutorials on how to establish this connection between the client browser and web server but very limited documentation on how to interact between two servers.

If one has set up Django Channels and listening to incoming connections i.e. on 127.0.0.1:8001

So your consumers.py would have a code such as ws_message where your route for any incoming messages. It would simply echo out what it receives to the terminal.

from channels import Group
def ws_message(message):
    print(message.content['text'])
    Group('chat').send({
        'text': 'user %s' % message.content['text'],
    })

Then, if you want to establish a connection from your other server (maybe a microcontroller transmitting data) the following code will send data to the specified address of 127.0.0.1:8001. Please note that you'll need websocket package for python for be sure to do

pip install websocket

server-socket.py

import websocket
import _thread as thread
import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print('Closed Connection')

def on_open(ws):
    def run(*args):
        for i in range(100):
            time.sleep(1)
            ws.send("%d" % i)
        time.sleep(1)
        ws.close()
        print ("thread terminating...")
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://127.0.0.1:8001",
                                 on_message = on_message,
                                 on_error = on_error,
                                 on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

It is fairly straightforward. It sends numbers in range of 0-99 to the connected websocket.

Upvotes: 1

Related Questions