[英]How to send data to a websocket from outside of consumer django channels
[英]Send data to a Django channels consumer
我有以下基本的 Django 頻道消費者:
class EchoConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
await self.accept()
await self.send_json('Connected!')
而且,並行地,我有一個普通的 Python 腳本,它連接到 websocket 並實時接收一些數據:
from binance.client import Client
import json
from binance.websockets import BinanceSocketManager
client = Client('', '')
# get all symbol prices
prices = client.get_all_tickers()
trades = client.get_recent_trades(symbol='BNBBTC')
# start aggregated trade websocket for BNBBTC
def process_message(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, Quantity, Order)
bm = BinanceSocketManager(client)
bm.start_trade_socket('BNBBTC', process_message)
bm.start()
我想做以下事情:第二個腳本應該以某種方式將該數據發送到 Django Channels 消費者,而不是只打印接收到的數據。 每當用戶打開頁面時,該頁面都應該收到該數據。 如果第二個用戶同時打開該頁面,則該第二個用戶也應該收到數據。 是否有可能做到這一點? 我應該使用其他服務嗎?
因此,如果您想將此數據發送到所有當前open
的 websocket 連接,您可以執行以下操作。
class EchoConsumer(AsyncJsonWebsocketConsumer):
groups = ["echo_group"]
async def on_message(self, message):
await self.send_json(... something here based on the message ... )
然后在您的腳本中,您需要導入channels
(並配置 django,因此最好將其django
命令,請參閱: https://docs.djangoproject.com/en/3/0/0.
from channels.layers import get_channel_layer
channel_layer = get_channel_layer()
... your other stuff to connect to
def process_message(message):
JSON1 = json.dumps(message)
JSON2 = json.loads(JSON1)
#define variables
Rate = JSON2['p']
Quantity = JSON2['q']
Symbol = JSON2['s']
Order = JSON2['m']
async_to_sync(channel_layer.group_send)(
"echo_group",
{"type": "on.message", "rate":Rate, "quantity": Quantity, "symbol": Symbol, "order": Order},
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.