所以我想用 is 来从套接字类获取数据
class BinanceWebSocket:
def __init__(self, symbol, interval):
self.symbol = symbol
self.interval = interval
self.latest_price_info = None
self.closes = Queue()
self.is_force_stopped = False
def on_message(self, ws, message):
data = json.loads(message)
if "k" in data and data["k"]["x"] == True:
kline = data["k"]
time = data["k"]["T"] / 1000
print(datetime.fromtimestamp(time))
# print(kline)
close = kline["c"]
self.latest_price_info = close
print(
"From WEBSOCKET - Latest current price updated: ",
self.latest_price_info,
)
data_to_send = self.get_data_to_send()
self.ws.send(json.dumps(data_to_send))
async def get_data_to_send(self):
data = {
"symbol": self.symbol,
"interval": self.interval,
"latest_price": self.latest_price_info,
}
在我的消费者阶层,我正在尝试做
class BinanceConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
self.binance_ws = BinanceWebSocket(symbol, interval, ma_length)
asyncio.ensure_future(self.update_data())
async def disconnect(self, close_code):
pass
async def update_data(self):
try:
while True:
data_to_send = await self.binance_ws.get_data_to_send()
print("Data received from BinanceWebSocket:", data_to_send)
await self.send(text_data=json.dumps({"data": data_to_send}))
await asyncio.sleep(1)
except asyncio.CancelledError:
pass
但是我得到了在构造函数中初始化的默认值,因此我无法从消费者中的 on_message 方法获取值,任何人都可以帮助我吗?
对像这里这样的异步库没有信心,但你可能会忘记
return
上的 get_data_to_send
方法:
async def get_data_to_send(self):
return {
"symbol": self.symbol,
"interval": self.interval,
"latest_price": self.latest_price_info,
}