在 Flask 中启动和停止线程
Start and Stop thread inside Flask
我想知道在 Flask 中结束线程作业是否需要做一些特别的事情?这是示例代码:
from flask import (
Flask, jsonify, render_template, request
)
import threading
import time
import random
app = Flask(__name__)
def task(thread_return):
random_seconds=random.random()
print(f'Start task {threading.current_thread().name} ')
time.sleep(random_seconds*15)
print(f'completed {threading.current_thread().name} ')
thread_return['seconds']= random_seconds*5
thread_return = {'seconds': 0}
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("index-ajax.html")
val = request.json.get("c_check")
t =threading.Thread(target=task, args=(thread_return,), daemon=True)
if val==1:
print("val1 is ", val)
t.start()
elif val==0:
try:
print('trying to kill thread')
exit_event= threading.Event()
exit_event.set()
except Exception as e:
print(e)
print("val0 is ", val)
return jsonify({"data": {"val": val}})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5000, debug=True)
我尝试结合我在网上看到的几个例子,将任务函数包装在 class 中,但它没有用,即:
我喜欢另一个例子,但我也无法让它与 Flask 一起工作:
How Do You Kill a Python Thread
感谢您的帮助。
我尝试多次重写并注意到以下工作。显然,我需要
- 在路由函数之外声明 threading.event()
- 在任务函数中设置exit_event.set()来结束任务或阻止任务运行
- 并修改任务函数以更好地模拟长期或不确定的 运行 任务
也许其他人有更优雅的 pythonic 解决方案。
from flask import (
Flask, jsonify, render_template, request
)
import threading
import time
import random
app = Flask(__name__)
def task(thread_return):
i=0
while True:
if exit_event.is_set():
print(f'end {threading.current_thread().name} ')
return
i+=1
random_seconds=random.random()
print(f'Running task {threading.current_thread().name} {i} sec elapsed')
time.sleep(1)
exit_event= threading.Event()
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("index-ajax.html")
val = request.json.get("c_check")
exit_event.clear()
t =threading.Thread(target=task, args=(thread_return,), daemon=True)
if val==1:
print("val1 is ", val)
t.start()
elif val==0:
try:
print('trying to end thread')
exit_event.set()
except Exception as e:
print(e)
print("val0 is ", val)
return jsonify({"data": {"val": val}})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5000, debug=True)
我想知道在 Flask 中结束线程作业是否需要做一些特别的事情?这是示例代码:
from flask import (
Flask, jsonify, render_template, request
)
import threading
import time
import random
app = Flask(__name__)
def task(thread_return):
random_seconds=random.random()
print(f'Start task {threading.current_thread().name} ')
time.sleep(random_seconds*15)
print(f'completed {threading.current_thread().name} ')
thread_return['seconds']= random_seconds*5
thread_return = {'seconds': 0}
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("index-ajax.html")
val = request.json.get("c_check")
t =threading.Thread(target=task, args=(thread_return,), daemon=True)
if val==1:
print("val1 is ", val)
t.start()
elif val==0:
try:
print('trying to kill thread')
exit_event= threading.Event()
exit_event.set()
except Exception as e:
print(e)
print("val0 is ", val)
return jsonify({"data": {"val": val}})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5000, debug=True)
我尝试结合我在网上看到的几个例子,将任务函数包装在 class 中,但它没有用,即:
我喜欢另一个例子,但我也无法让它与 Flask 一起工作: How Do You Kill a Python Thread
感谢您的帮助。
我尝试多次重写并注意到以下工作。显然,我需要
- 在路由函数之外声明 threading.event()
- 在任务函数中设置exit_event.set()来结束任务或阻止任务运行
- 并修改任务函数以更好地模拟长期或不确定的 运行 任务
也许其他人有更优雅的 pythonic 解决方案。
from flask import (
Flask, jsonify, render_template, request
)
import threading
import time
import random
app = Flask(__name__)
def task(thread_return):
i=0
while True:
if exit_event.is_set():
print(f'end {threading.current_thread().name} ')
return
i+=1
random_seconds=random.random()
print(f'Running task {threading.current_thread().name} {i} sec elapsed')
time.sleep(1)
exit_event= threading.Event()
@app.route("/", methods=["GET", "POST"])
def index():
if request.method == "GET":
return render_template("index-ajax.html")
val = request.json.get("c_check")
exit_event.clear()
t =threading.Thread(target=task, args=(thread_return,), daemon=True)
if val==1:
print("val1 is ", val)
t.start()
elif val==0:
try:
print('trying to end thread')
exit_event.set()
except Exception as e:
print(e)
print("val0 is ", val)
return jsonify({"data": {"val": val}})
if __name__ == "__main__":
app.run(host="127.0.0.1", port=5000, debug=True)