[英]Passing argument in thread without invoking - how to put Flask server in thread
如何使用自定義 ip(監聽網絡)在線程中啟動 flask 服務器?
此行不會阻塞主線程,但不會監聽來自網絡的連接。
threading.Thread(target = app.run).start()
當它被使用時,它會等待這個線程完成,並且主線程被阻塞。
#threading.Thread(target = app.run(host='192.168.1.42')).start()
我嘗試制作游戲,Pygame 在主線程中運行,flask 服務器用於托管網頁,為玩家提供操縱桿。
目前我可以用本地機器控制它,但不能通過手機控制。 如果我用自定義 ip 配置 flask,主線程將停止等待服務器線程。
這與調用和引用有關,但我不知道如何使用參數設置線程,但不調用。
整個 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.