正如您自己所说,脚本运行良好。所以现在发生的事情是烧瓶正在创建线程来满足您的请求。您发送第一个请求,flask 在一个线程上启动一个计数器,当您发送另一个请求时,flask 启动另一个线程,另一个计数器在该线程上运行。两个线程都有自己的值speed、thetime 和cents,一个线程不能更改另一个线程中变量的值。
所以我们要做的是从任何线程访问/修改变量的值。一种简单的解决方案是使用全局变量,以便所有线程都可以访问这些变量。
解决方案:
- 将
speed、thetime 和cents 设为全局变量,以便可以从任何线程修改它们。
- 当我们收到请求时,检查计数器是否已经在运行(我们可以通过检查全局变量
thetime 的值是否为 0 来做到这一点。
- 我们知道现有计数器是否正在运行,现在只需更新全局变量的值。
- 如果没有现有的计数器在运行,则启动计数器(调用方法
countdown())。否则我们不需要做任何事情(我们已经在上一步更新了全局变量的值,所以现有的计数器也会更新)。
代码:
import time
from flask import Flask, request
app = Flask(__name__)
# We create global variables to keep track of the counter
speed = thetime = cents = 0
@app.route('/', methods=["GET"])
def post():
global speed, thetime, cents
# Check if previous counter is running
counter_running = True if thetime else False
thetime = int(request.args["time"])
speed = float(request.args["speed"])
cents = request.args["cents"]
print('\n')
print('AccuView Digital:')
print('Speed:', speed, ' Time:', thetime, ' Cents:', cents)
print('-------------------------------')
def countdown():
global thetime, speed
while thetime:
mins, secs = divmod(thetime, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print('Tijd:', timer, end="\r")
time.sleep((speed + 1) / 1000)
thetime -= 1
if thetime == 0:
print('Werp geld in\n')
# If existing counter is running, then we don't start another counter
if not counter_running:
countdown()
return '1'
app.run(host='192.168.1.107', port= 8090)
代码(以便我们可以中断睡眠):
import time
import threading
from flask import Flask, request
app = Flask(__name__)
# We create global variables to keep track of the counter
speed = thetime = cents = 0
sleep_speed = threading.Event()
@app.route('/', methods=["GET"])
def post():
global speed, thetime, cents, sleep_speed
# Check if previous counter is running
counter_running = True if thetime else False
thetime = int(request.args["time"])
speed = float(request.args["speed"])
cents = request.args["cents"]
# Make sure to interrupt counter's sleep
if not sleep_speed.is_set():
sleep_speed.set()
sleep_speed.clear()
print('\n')
print('AccuView Digital:')
print('Speed:', speed, ' Time:', thetime, ' Cents:', cents)
print('-------------------------------')
def countdown():
global thetime, speed
while thetime:
mins, secs = divmod(thetime, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print('Tijd:', timer, end="\r")
sleep_speed.wait((speed + 1) / 1000)
thetime -= 1
if thetime == 0:
print('Werp geld in\n')
# If existing counter is running, then we don't start another counter
if not counter_running:
countdown()
return '1'
app.run(host='0.0.0.0', port=8090)