python - 无法将 websocket 数据流式传输到前端
问题描述
我正在尝试通过他们的 websockets sdk 将来自股票经纪人(Zerodha)的市场实时数据流式传输到我的前端。
我能够在我的 python 控制台中记录实时数据,但我无法将其流式传输到前端。
我是套接字编程的新手,所以请原谅。
下面是python片段。
import json
from flask import Flask, render_template, request, redirect, session
import threading
import time
from kiteconnect import KiteTicker #WebSocket client for connecting to Kite Connect's streaming quotes service.
import logging
###
from flask_socketio import SocketIO, emit
###
app = Flask(__name__)
##
socketio = SocketIO(app, async_mode= 'threading')
##
app.config['DEBUG'] = False
ticker = None
@app.route('/streamData')
def streamData():
'''
to start stream we first have to
1.) initiliase a WS connection - done
2.) Subscribe/register the symbols - done
3.) Check on new ticks - done
4.) To do: kill the ws after x time
'''
global ticker
accessToken = getAccessToken()
ticker = KiteTicker("api key here", accessToken)#1
# Assign the callbacks.
ticker.on_connect = onConnectLocal
ticker.on_close = onDisconnectLocal
ticker.on_error = onErrorLocal
ticker.on_ticks = onNewTicksLocal#3
logging.info('Ticker: Going to connect..')
ticker.connect(threaded=True)
time.sleep(5)
symbols = ['stock', 'names', 'given', 'here']
tokens = []
kite = getKite()
fetchInstruments(kite)
for symbol in symbols:
isd = getInstrumentDataBySymbol(symbol)
token = isd['instrument_token']
logging.info('registerSymbol: %s token = %s', symbol, token)
tokens.append(token)
logging.info('Subscribing tokens %s', tokens)
ticker.subscribe(tokens)#2
print(tokens)
return render_template('stream.html', async_mode='threading') # here is where I want to stream the data
def onConnectLocal(ws, response):
logging.info('Ticker connection successful.')
def onDisconnectLocal(ws, code, reason):
logging.error('Ticker got disconnected. code = %d, reason = %s', code, reason)
def onErrorLocal(ws, code, reason):
logging.error('Ticker errored out. code = %d, reason = %s', code, reason)
#@socketio.on('my_broadcast_event', namespace='/test')
def onNewTicksLocal(ws, ticks):#3 # this the method which streams data from the broker's websocket
for tick in ticks:
isd = getInstrumentDataByToken(tick['instrument_token'])
symbol = isd['tradingsymbol']
logging.info('Tick: %s CMP = %f', symbol, tick['last_price']) #this prints to the python console with no problem
socketio.emit('my_response',{'data': tick}, broadcast=True)# this makes the problem
app.run('localhost', 8080)
stream.html(前端)
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
namespace = 'http://localhost:8080/streamData';
var socket = io(namespace);
socket.on('connect', function() {
socket.emit('my_event', {data: 'connected to the SocketServer...'});
});
socket.on('my_response', function(msg, cb) {
$('#log').append('<br>' + $('<div/>').text('logs #' + msg.count + ': ' + msg.data).html());
if (cb)
cb();
});
$('form#emit').submit(function(event) {
socket.emit('my_event', {data: $('#emit_data').val()});
return false;
});
$('form#broadcast').submit(function(event) {
socket.emit('my_broadcast_event', {data: $('#broadcast_data').val()});
return false;
});
$('form#disconnect').submit(function(event) {
socket.emit('disconnect_request');
return false;
});
socket.on('my_response', function(data){
console.log(data.msg)
socket.emit('my_response', {data: data.msg});
});
});
</script>
我总是得到的错误是: -
TypeError: onNewTicksLocal() missing 1 required positional argument: 'ticks'
但是正如你在上面看到的,我已经提供了这个(当我点击广播按钮时出现这个错误)。
请让我知道我哪里出错了(我觉得,但不确定,回调可能会出错)。
编辑:- 更新了 python 中的 html 代码和端口号
解决方案
推荐阅读
- c++ - 如何在类中实现“模板”?我的代码有问题吗?
- html - socket .io 房间中的投票(投票)
- java - Spring Boot MongoDB:可以使用@GeneratedValue 和@Column 注解吗?
- python - 我正在用python制作一个excel pdf,但是excel中的图像质量变差了
- r - 如果当前列不为空,则聚合下一列的值
- angular - Angular Mat-Icon 仅显示文本(不显示 img)
- swagger - 对 fastify swagger 的标记支持
- node.js - 使用 kerberos 快速连接到 Oracle DB
- javascript - 在所有角度元素项目中共享一个角度库实例
- java - 允许基于用户角色访问控制器。所有这些都是403错误