【问题标题】:background task does not emit后台任务不发出
【发布时间】:2025-10-22 14:10:02
【问题描述】:

有很多可用于 Flask 和 SocketIO 的教程,我找不到任何我理解的简单线程方法。但我确实阅读并关注了其中的许多内容。 我想使用 websockets 在网页上展示我的 Python 应用程序,所以它是一种实时监控。这是我试图了解如何实现这一点。

除了发射部分之外,我目前拥有的代码正在工作。似乎没有任何数据传输。我想知道为什么。

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>

【问题讨论】:

    标签: python-3.x flask socket.io


    【解决方案1】:

    我的错误在线:thread = socketio.start_background_task(target=counter())

    在那里我引用了作为后台任务运行的函数,但我使用 () 的符号,这是不允许的,因为它运行函数并且没有为 start_background_task 提供对此函数的引用。

    【讨论】: