如何在线程中运行Flask SocketIO?

时间:2019-09-10 22:49:46

标签: python-3.x flask

我正在尝试使用Python 3在线程中运行Flask SocketIO,但无法使其正常工作。

我的代码不会在while循环中继续。

如何在线程中运行它?

import threading
from flask import Flask, render_template, request, redirect, url_for
from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'


#turn the flask app into a socketio app
socketio = SocketIO(app)


@app.route("/")
def index():
   return render_template('index.html', **templateData)

if __name__ == "__main__":
   threading.Thread(target=socketio.run(app),kwargs=dict(debug=False, use_reloader=False,host='0.0.0.0', port=5000)).start()
   sleep(2)

   while True:
       try:
           Print("Hello I'm in a while loop")

       except KeyboardInterrupt:
           sys.exit()

1 个答案:

答案 0 :(得分:1)

您应将socketio.run作为target传递,并将app作为参数传递

threading.Thread(
    target=socketio.run,
    args=(app,),
    kwargs=dict(debug=False, use_reloader=False,host='0.0.0.0', port=5000)
).start()

似乎也忘记了从时间导入睡眠

from time import sleep

,还请注意,templateData未在代码中定义