Python 如何取消「;“开始”;使用“请求”;停止“;烧瓶里的请求?

Python 如何取消「;“开始”;使用“请求”;停止“;烧瓶里的请求?,python,flask,Python,Flask,单击Web UI上的“开始”按钮时,程序计划使用threading.Timer()处理数据,频率为0.01s,在5000步内。“停止”按钮用于随时停止处理_data(),并返回在此期间计算的部分结果 step = 0 result = {} thread = None @app.route('/start', methods=['GET']) def start(): processing_data() time.sleep(5000*0.01) # wait for the

单击Web UI上的“开始”按钮时,程序计划使用threading.Timer()处理数据,频率为0.01s,在5000步内。“停止”按钮用于随时停止处理_data(),并返回在此期间计算的部分结果

step = 0
result = {}
thread = None

@app.route('/start', methods=['GET'])
def start():
    processing_data()
    time.sleep(5000*0.01) # wait for the processing_data() finished
    return Response(result, mimetype='application/json')

def processing_data():
    result = {json : format} # compute the json format result
    if step != 5000:
        global step
        step +=1
        global thread
        thread = threading.Timer(0.01, processing_data)
        thread.start()

@app.route('/stop', methods=['GET'])
def stop():
    thread.cancel()
    return "stopped"
它不起作用,似乎stop()只能在start()完成后运行。所以我的问题是如何在处理过程中取消start()请求?假设用户不耐烦,谁只想在某些步骤后得到计算结果的一部分

编辑: 我试图进一步简化程序,删除线程,添加Flask的应用程序上下文。这一切都是一样的,这意味着线程不是问题所在,请求或sleep()不能被中断

step = 0
result = {}

@app.route('/start', methods=['GET'])
def start():
    g.__stop = False
    processing_data()
    time.sleep(5000*0.01) # wait for the processing_data() finished
    return Response(result, mimetype='application/json')

def processing_data():
    result = {json : format} # compute the json format result
    if step != 5000 and not g.__stop:
        global step
        step +=1
        processing_data()

@app.route('/stop', methods=['GET'])
def stop():
    g.__stop = True
    return "stopped"

嗯。。。您正试图修改全局
步骤
变量,但未将其声明为全局变量。因此它实际上根本没有改变全局
步骤
,这将创建一个无限系列的线程(与
结果
相同)。对不起,我只是简化了我的程序,所以可能有错误,可能全局线程是个坏主意,我稍后会修复它。现在我只是想知道,有没有可能在烧瓶里取消这样一条线?是的,有可能。但这不是一个好主意。您通常会在WSGI之类的东西后面运行这个过程。在本例中,您将有多个进程。当您请求/停止时,无法知道您已经停止了它,因为该线程可能位于与处理您的请求的线程不同的进程上。你应该用芹菜之类的东西来做这个。