Jack022
Jack022

Reputation: 1257

Send data to frontend with Django channels

I created a Django channels consumer that, once the connection is open, should establish a connection to an external service, retrieve some data from this service and send the data to my frontend.

Here is what i tried:

import json
from channels.generic.websocket import WebsocketConsumer, AsyncConsumer, AsyncJsonWebsocketConsumer
from binance.client import Client
from binance.websockets import BinanceSocketManager
import time
import asyncio

client = Client('', '')

trades = client.get_recent_trades(symbol='BNBBTC')

class EchoConsumer(AsyncJsonWebsocketConsumer):

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

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


    def process_message(self, 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)

When the connection is opened, this code will start printing some market orders to my console as soon as there is one. Now, instead of printing them to my console, i would like to send them to my frontend. Can someone explain me how to do that?

Here is my frontend:

{% load staticfiles %}
<html>
  <head>
    <title>Channels</title>
  </head>
  <body>
    <h1>Testing Django channels</h1>
    <script>
    // websocket scripts
    var loc = window.location
    var wsStart = 'ws://' + window.location.host + window.location.pathname
    var endpoint = wsStart + loc.host + loc.pathname
    var socket = new WebSocket(endpoint)

    if (loc.protocol == 'https:'){
      wsStart = 'wss://'
    }

    socket.onmessage = function(e){
      console.log("message", e)
    }

    socket.onopen = function(e){
      console.log("message", e)
    }

    socket.onerror = function(e){
      console.log("message", e)
    }

    socket.onclose = function(e){
      console.log("message", e)
    }
    </script>
  </body>
</html>

Upvotes: 3

Views: 2363

Answers (1)

Anton Pomieshchenko
Anton Pomieshchenko

Reputation: 2167

Modify function process_message, add sending data using websockets:

def process_message(self, message):
    asyncio.create_task(self.send_json(message))

Upvotes: 1

Related Questions