将数据发送到Django通道的前端

问题描述 投票:1回答:1

我创建了一个Django渠道使用者,一旦连接打开,就应该建立与外部服务的连接,从该服务中检索一些数据并将该数据发送到我的前端。

这是我尝试过的:

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)

打开连接后,此代码将在有控制台的情况下立即开始向我的控制台打印一些市场订单。现在,我不想将它们打印到我的控制台上,而是想将它们发送到我的前端。有人可以解释我该怎么做吗?

这是我的前端:

{% 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>
python django django-channels
1个回答
0
投票

修改函数process_message,使用websocket添加发送数据:

def process_message(self, message):
    asyncio.create_task(self.send_json(message))
© www.soinside.com 2019 - 2024. All rights reserved.