Сценарий работает нормально, как вы сказали сами. Так что сейчас происходит то, что flask создает потоки для обслуживания ваших запросов. Вы отправляете 1-й запрос, flask запускает счетчик в одном потоке, а когда вы отправляете другой запрос, flask запускает другой поток, и в этом потоке запускается другой счетчик. Оба потока имеют свои собственные значения speed
, thetime
и cents
, и один поток не может изменить значение переменной в другом потоке.
Поэтому мы хотим получить доступ / изменить значение переменных из любого потока. Одним из простых решений для этого является использование глобальных переменных, чтобы эти переменные были доступны из всех потоков.
Решение:
- Make
speed
, thetime
и cents
как глобальные переменные, так что они могут изменяться из любого потока. - Когда мы получаем запрос, проверьте, работает ли счетчик (мы можем сделать это, проверив, является ли значение глобальной переменной
thetime
is 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)