【问题标题】:How to interface start function, stop function to start a indefinite while loop and stop it using flask?如何接口启动函数,停止函数以启动无限期的while循环并使用flask停止它?
【发布时间】:2026-01-13 13:50:01
【问题描述】:

这是我的问题 - 我正在使用带有 python 和 html 的烧瓶来创建一个网络应用程序。我要做的就是创建2个按钮,其中我的html中的一个按钮反过来在我的flask.py(服务器端)中启动一个while循环,即它调用一个计数器函数并连续运行,当按下另一个按钮时循环应该停止.我该怎么办?

【问题讨论】:

    标签: html python-3.x flask


    【解决方案1】:

    下面python端的最小可行示例。在 html 端,您的按钮调用 /start/stop 端点。 如果这不仅仅是概念证明或单用户应用程序,则不应像这样使用线程和全局变量。查看 Celery/RQ 以替换任务和 Redis/用于存储“全局”变量的数据库。

    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)
    

    【讨论】:

    • 谢谢!但是在 new /start 失败后,在 def start(): 添加 go = True 并且效果很好!