[Python Flask在新请求后更新var

问题描述 投票:1回答:1

我已经在Python中创建了一个简单的脚本(我是newby)。除了一个小问题,一切都按需工作。

我的项目:我通过http向我的服务器发送请求:{ip-of-server} /?speed = 999&time = 8&cents = 50

这将在您的shell中显示一个倒数计时器。在这种情况下,从8倒数到0。那很好。当我发送{ip-of-server} /?speed = 499&time = 8&cents = 50时,它的倒计时速度将是以前的两倍。这是根据需要的。

我面临的问题:在倒计时期间,我需要能够向我的服务器发送新请求。它应使用新值更新倒计时。目前,它将创建2个倒数计时。如果您阅读了脚本,那是正确的,但不是我所需要的。我需要一些如何更新现有倒计时的帮助。

我的代码:

from flask import Flask, request
app = Flask(__name__)
import time

@app.route('/', methods = ["GET"])

def post():
    speed = float(request.args["speed"])
    thetime = request.args["time"]
    cents = request.args["cents"]

    print('\n')
    print('AccuView Digital:')
    print('Speed:', speed,' Time:', thetime,' Cents:', cents)
    print('-------------------------------')

    def countdown(thetime):
        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') 
    countdown(int(thetime))
    return '1'

app.run(host='192.168.1.107', port= 8090)

谢谢

python flask python-requests countdown
1个回答
0
投票

如您自己所说,脚本运行良好。所以现在发生的事情是flask正在创建线程来满足您的请求。您发送第一个请求,flask在一个线程上启动一个计数器,当您发送另一个请求时,flask在另一个线程上启动,另一个计数器在该线程上运行。两个线程都有各自的speedthetimecents值,并且一个线程无法更改另一个线程中变量的值。

所以我们要做的是从任何线程访问/修改变量的值。一种简单的解决方案是使用全局变量,以便可以从所有线程访问这些变量。

解决方案:

  1. speedthetimecents设为全局变量,以便可以从任何线程进行修改。
  2. [当我们收到请求时,检查计数器是否已经在运行(我们可以通过检查全局变量thetime的值是否为0来做到这一点。]
  3. 我们知道现有计数器是否正在运行,现在只需更新全局变量的值。
  4. 如果没有正在运行的计数器,则启动计数器(调用方法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)
© www.soinside.com 2019 - 2024. All rights reserved.