1

I have the following basic Django Channels consumer:

class EchoConsumer(AsyncJsonWebsocketConsumer):

    async def connect(self):
        await self.accept()
        await self.send_json('Connected!')

And, in parallel, i have a normal Python script which connects to a websocket and receives some data in real time:

from binance.client import Client
import json
from binance.websockets import BinanceSocketManager

client = Client('', '')

# get all symbol prices
prices = client.get_all_tickers()


trades = client.get_recent_trades(symbol='BNBBTC')
# start aggregated trade websocket for BNBBTC
def process_message(message):
    JSON1 = json.dumps(message)
    JSON2 = json.loads(JSON1)

    #define variables
    Rate = JSON2['p']
    Quantity = JSON2['q']
    Symbol = JSON2['s']
    Order = JSON2['m']

    print(Rate, Quantity, Order)

bm = BinanceSocketManager(client)
bm.start_trade_socket('BNBBTC', process_message)
bm.start()

I would like to do the following: instead of only printing the data received, the second script should send somehow that data to the Django Channels consumer. Whenever a user opens the page, that page should receive that data. If a second user opens the page at the same time, that second user should receive the data too. Is it possible to do this? Am i supposed to use another service?

Jack022
  • 867
  • 6
  • 30
  • 91
  • From where would you like to send data to your Django Channels? There are lots of examples in other questions, for example: https://stackoverflow.com/questions/51725863/django-channels-constantly-send-data-to-client-from-server and https://stackoverflow.com/questions/57886187/how-to-create-task-which-sends-data-continuously-and-disconnect-safely-in-consum, https://medium.com/@ksarthak4ever/django-websockets-and-channels-85b7d5e59dda Have you tried any of these tutorials and ideas if they solve your issue? – Anastasiia Apr 09 '20 at 08:21
  • I have a 'data collector' application running on a server, then i have my Django app, i need to send data from my data collector to the Django app. I'm going to check out your tutorials! I think i found a solution for this, it would be a PUB/SUB system using Redis – Jack022 Apr 09 '20 at 08:24
  • Using a queue is a good solution ;-) – Anastasiia Apr 09 '20 at 08:27
  • Yes! Just need to see how scalable is this. I also thought of turning my data collector into a websocket server and connect to it straight from my Django frontend, but it will be a second option if this one does not work – Jack022 Apr 09 '20 at 08:29
  • Check also this example: https://steelkiwi.com/blog/websocket-server-on-aiohttp-in-django-project/ – Anastasiia Apr 09 '20 at 08:32
  • Checking it! Extremely interesting for this project, thank you! – Jack022 Apr 09 '20 at 08:34

1 Answers1

2

so if you want to send this data to all currently open websocket connections you can do the following.

class EchoConsumer(AsyncJsonWebsocketConsumer):

    groups = ["echo_group"]

    async def on_message(self, message):
       await self.send_json(... something here based on the message ... )

Then in your script you need to import channels (and have django configured so its best for this to be a django command see: https://docs.djangoproject.com/en/3.0/howto/custom-management-commands/

from channels.layers import get_channel_layer
channel_layer = get_channel_layer()

... your other stuff to connect to 

def process_message(message):
    JSON1 = json.dumps(message)
    JSON2 = json.loads(JSON1)

    #define variables
    Rate = JSON2['p']
    Quantity = JSON2['q']
    Symbol = JSON2['s']
    Order = JSON2['m']

   async_to_sync(channel_layer.group_send)(
        "echo_group",
        {"type": "on.message", "rate":Rate, "quantity": Quantity, "symbol": Symbol, "order": Order},
    )

Matthaus Woolard
  • 2,310
  • 11
  • 13
  • Hey! Thank you again! I'm going to accept this because it's a good way to go, I just have one problem: in my example I'm using one market called 'BNBBTC', but once i go forward i will have more markets (around 600), this is why i decided to create redis channels. To import my Django variables and broadcast the data, am I supposed to turn it into a Django management command or is there another way to do this? – Jack022 Apr 10 '20 at 07:56