我创建了一个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>
答案 0 :(得分:1)
修改函数process_message,使用websocket添加发送数据:
def process_message(self, message):
asyncio.create_task(self.send_json(message))