在不调用的情况下在线程中传递参数 - 如何将 Flask 服务器放入线程中

Passing argument in thread without invoking - how to put Flask server in thread

如何使用自定义 ip(监听网络)在线程中启动 flask server?

此行不会阻塞主线程,但不会侦听来自网络的连接。

threading.Thread(target = app.run).start()

当它被使用时,它等待这个线程完成,主线程被阻塞。

#threading.Thread(target = app.run(host='192.168.1.42')).start()

我试过做游戏,Pygame在主线程中运行,flask服务器用于托管网页,为玩家提供操纵杆。

目前我可以用本地机器控制它,但不能通过手机。如果我用自定义 ip 配置烧瓶,主线程将停止等待服务器线程。

这与调用和引用有关,但我不知道如何设置带参数的线程,但没有调用。

整个 pycharm 项目在 GitHUB

这是server.py

from flask import Flask,render_template,request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
import threading


def initServer(controlDataToPyGame):  #argument is queue for transferring data to main thread


    app = Flask(__name__)
    app.debug= False


    @app.route('/')

    def index():
        print("index")
        return render_template('index.html')

    @app.route('/play/')
    def play():
        print("play")
        return render_template('controller.html')

    @app.route("/Control/")
    def UP():
        x = request.args.get('joyX')
        y = request.args.get('joyY')

        controlDict = {"name":"ice", "x":x,"y":y}
        controlDataToPyGame.put(controlDict)

        return ("nothing")


    ##this doesn't block the main thread,  but it doesn't listen connections from the network.
    threading.Thread(target = app.run).start()

    #when this is used it waits to this thread to finish, and main thread is blocked.
    #threading.Thread(target = app.run(host='192.168.1.42')).start()

如果您阅读 Thread 的文档,您会看到 args=kwargs=

threading.Thread(target=app.run, kwargs={'host': '192.168.1.42'}).start()

正在使用

threading.Thread(target = app.run(host='192.168.1.42')).start()

你只需 运行 app.run() 然后将其结果发送到 Thread 就像

result = app.run(host='192.168.1.42')
Thread(target=result).start()

并且它 运行s app.run() 永远在主线程中 - 它从不使用 Thread