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 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)

And my HTML template:

  <!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>

1 Answers

0
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.