如何接口启动功能,停止功能,以启动一个无限期的while循环,并停止它使用烧瓶?



这是我的问题-我使用flask与python和html来创建一个web应用程序。我所要做的就是创建2个按钮,其中一个按钮在我的html中,在我的flask.py(服务器端)中开始一个while循环,即它调用计数器函数并连续运行,当另一个按钮按下循环时应该停止。我该怎么做呢?

下面的python端最小可行示例。在html端有你的按钮调用/start/stop端点。如果这不仅仅是概念证明或单用户应用程序,那么线程和全局变量就不应该这样使用。考虑芹菜/RQ来取代任务和Redis/a数据库来存储"全局";变量。

from flask import Flask
from threading import Thread
from time import sleep
app = Flask(__name__)
go = True
count = 0
def counter():
global go
while go:
sleep(1)
global count
count += 1
print(count)
@app.route('/start', methods=('GET','POST'))
def start():
thread = Thread(target=counter)
thread.start()
return 'Started'
@app.route('/stop', methods=('GET','POST'))
def check():
global go
go = False
return 'Stopped at: ' + str(count)
app.run(debug=True)

最新更新