如何解决在线程中传递参数而不调用 - 如何将 Flask 服务器置于线程中
如何在具有自定义 ip(侦听网络)的线程中启动 Flask 服务器?
此行不会阻塞主线程,但不会侦听来自网络的连接。
threading.Thread(target = app.run).start()
当使用它时,它等待该线程完成,并且主线程被阻塞。
#threading.Thread(target = app.run(host='192.168.1.42')).start()
我尝试制作游戏,Pygame 在主线程中运行,flask 服务器用于托管网页,为玩家提供操纵杆。p>
目前我可以用本地机器控制它,但不能通过手机控制。如果我用自定义 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()
并且它永远在主线程中运行 app.run()
- 它从不使用 Thread
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。