background task does not emit

Asked by At

There are many tutorials available for Flask and SocketIO, I could not find any for a simple threaded approach that I understood. But I did read and followed many of them. I'd like to show my Python application on a web page using websockets so it's kind-of real-time monitoring. This is me trying to understand how to implement this.

The code I currently have is working for except the emit part. There does not seem to be any transfer of data. I'd like to know why.

The socket.on('tingeling' ... is not being triggered.

My Python code, mostly taken from

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.emit('tingeling', counting, namespace='')
        print(f"Counter: {counting}")

def sessions():
    return render_template('index.html')

@socketio.on('my event')
def connected(data):
    print('my event')

def starten():
    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__':, debug=True)

And my HTML template:

  <!DOCTYPE html>
  <html lang="en">

    <h3 style='color: #ccc;font-size: 30px;'>waiting</h3>

    <script src=""></script>
    <script src=""></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')



1 Answers

Thijs On

My error is on the line: thread = socketio.start_background_task(target=counter())

There I reference the function to run as a background task but I use the notation with () and that is not allowed because is runs the function and does not provide the start_background_task with a reference to this function.