3

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>

1 Answer 1

1

Modify function process_message, add sending data using websockets:

def process_message(self, message):
    asyncio.create_task(self.send_json(message))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! You solved a problem that tormented me for 4 days! Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.