Python 使用Django通道将数据发送到前端
我创建了一个Django Channel consumer,一旦连接打开,它应该建立到外部服务的连接,从该服务检索一些数据,并将数据发送到我的前端 以下是我尝试过的:Python 使用Django通道将数据发送到前端,python,django,django-channels,Python,Django,Django Channels,我创建了一个Django Channel consumer,一旦连接打开,它应该建立到外部服务的连接,从该服务检索一些数据,并将数据发送到我的前端 以下是我尝试过的: import json from channels.generic.websocket import WebsocketConsumer, AsyncConsumer, AsyncJsonWebsocketConsumer from binance.client import Client from binance.websock
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>
{%load staticfiles%}
渠道
测试Django通道
//websocket脚本
var loc=窗口位置
var wsStart='ws://'+window.location.host+window.location.pathname
var endpoint=wsStart+loc.host+loc.pathname
var套接字=新的WebSocket(端点)
如果(loc.protocol==“https:”){
wsStart='wss://'
}
socket.onmessage=函数(e){
控制台日志(“消息”,e)
}
socket.onopen=函数(e){
控制台日志(“消息”,e)
}
socket.onerror=函数(e){
控制台日志(“消息”,e)
}
socket.onclose=函数(e){
控制台日志(“消息”,e)
}
修改功能处理\u消息,使用WebSocket添加发送数据:
def process_message(self, message):
asyncio.create_task(self.send_json(message))
非常感谢。你解决了一个折磨我4天的问题!谢谢!