我还没有找到一个将Python WebSocket客户端连接到Plotly Dash的例子,我想知道设计它的最好方法是什么。我的Websocket服务器监听股票交易流的实现,看起来像这样:
class StockSocket:
def __init__(self):
self.underlying_symbol = underlying_symbol
self.last_underlying_price = ''
def on_message(self, ws, message):
m = json.loads(message)
self.last_underlying_price = str(m['last'])
# I want to send this message to client here
def on_error(self, ws, error):
print(error)
def on_close(self, ws, close_status_code, close_msg):
print("### closed ###")
def on_open(self, ws):
payload = json.dumps({"symbol": self.underlying_symbol, "sessionid": self.sessionId})
ws.send(payload)
def run_forever(self):
websocket.WebSocketApp("<market-feed-url>",on_open=self.on_open, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close).run_forever()
def runWebsocket(sessionId, underlying_symbol):
ws = StockSocket(sessionId, underlying_symbol)
ws.run_forever()
我计划通过Python Flask服务器运行这个程序,然后让Dash WebSocket监听,但是我不太确定这个实现。
对于客户端代码,我的想法如下:
import dash_core_components as dcc
import dash_html_components as html
import dash_extensions as de
from dash import Dash
from dash.dependencies import Input, Output
# Create example app.
app = Dash(prevent_initial_callbacks=True)
app.layout = html.Div([
dcc.Input(
id="input", autoComplete="off"
),
html.Div(id="msg"),
de.WebSocket(url="ws://localhost:8000/", id="ws")
])
# Send input value using websocket.
send = "function(value){return value;}"
app.clientside_callback(
send,
Output("ws", "send"),
[Input("input", "value")],
)
# Update div using websocket.
receive = "function(msg){console.log(msg.data); return \"Response from websocket: \" + msg.data;}"
app.clientside_callback(
receive,
Output("msg", "children"),
[Input("ws", "message")]
)
if __name__ == '__main__':
app.run_server(host='0.0.0.0', port=8000, debug=True, use_reloader=False)
我的两个主要问题是:
1.如何使用Python WebSocket库将消息从服务器发送到客户端(文档很少)
1.客户端如何轮询服务器?
谢谢你!
1条答案
按热度按时间s3fp2yjn1#
python中的通用WebSocket是这样的:
但你可以从这里得到你需要的一切:
https://pypi.org/project/websockets/
然后在这里:
https://websockets.readthedocs.io/en/stable/intro/index.html