Существует множество учебных пособий для Flask и SocketIO, я не смог найти ни одного для простого многопоточного подхода, который я понял.Но я прочитал и следовал за многими из них.Я хотел бы показать свое приложение Python на веб-странице с использованием веб-сокетов, так что это своего рода мониторинг в реальном времени.Это я пытаюсь понять, как реализовать это.
Код, который у меня сейчас есть, работает, кроме части emit.Кажется, что нет передачи данных.Я хотел бы знать, почему.
socket.on('tingeling' ...
не запускается.
Мой код Python, в основном взят из https://codeburst.io/building-your-first-chat-application-using-flask-in-7-minutes-f98de4adfa5d
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = ''
socketio = SocketIO(app)
thread = None
def counter():
print("counter ding")
counting = 0
while True:
counting += 1
socketio.sleep(2)
socketio.emit('tingeling', counting, namespace='')
print(f"Counter: {counting}")
@app.route('/')
def sessions():
print('route')
return render_template('index.html')
@socketio.on('my event')
def connected(data):
print('my event')
@socketio.on('connect')
def starten():
print("connect")
socketio.emit('tingeling', 'start')
global thread
if thread is None:
print('thread ding')
thread = socketio.start_background_task(target=counter())
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app, debug=True)
И мойHTML-шаблон:
<!DOCTYPE html>
<html lang="en">
<head>
<title>fristi</title>
</head>
<body>
<h3 style='color: #ccc;font-size: 30px;'>waiting</h3>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script type="text/javascript">
var socket = io.connect('http://' + document.domain + ':' + location.port);
console.log('doet iets')
socket.on( 'connect', function() {
socket.emit( 'my event', {
data: 'User Connected'
})
})
socket.on('tingeling', function(msg) {
console.log('iets komt binnen')
console.log(msg)
})
</script>
</body>
</html>