如何在生产模式下运行 Flask 应用程序时停止无限循环

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

我有 Flask 应用程序。它有两个按钮开始和停止

from flask import Flask, render_template
import sys
flag1=True
app = Flask(__name__)

@app.route('/')
def index():
  return render_template('index.html')

@app.route('/start/')
def start():
  globals()['flag1']=True
  while flag1==True:
    print('pStart')
  return render_template('index.html')

@app.route('/stop/')
def stop():
  globals()['flag1']=False
  return render_template('index.html')

if __name__ == '__main__':
  app.run(host='0.0.0.0')

这是我的模板\index.html

<!doctype html>


<head><title>Test</title> 
    <meta charset=utf-8>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

    </head>
    <body>
        <h1>My Website</h1>
<a href="http://localhost:5000/start/">Start</a> 

<a href="http://localhost:5000/stop/">Stop</a> 
    
    </body>

此应用程序在开发模式下运行良好。然而,当我用 uWSGI 运行它时,我无法停止它(无限循环的 print('pStart'))。 这是我的 wsgi.py

from myproject import app

if __name__ == "__main__":
    app.run()

uwsgi --socket 0.0.0.0:5000 --protocol=http -w wsgi:app

我尝试使用全局变量、线程、多处理来编写这个应用程序。我想在单击“停止”按钮时停止运行“print('pStart')”(当我使用 uWSGI 或任何其他服务器在生产模式下运行 Flask 应用程序时)。

python flask uwsgi
1个回答
0
投票

start
函数中的while循环无限运行,无法处理传入的请求。因此,当您在生产模式下运行应用程序时,服务器无法在调用
start
函数后处理任何传入请求!

您可以使用后台任务连续运行

print('pStart')
,同时允许 Flask 应用程序处理传入的请求,为此使用线程模块。

以下是如何使用线程在后台创建函数:

  from flask import Flask, render_template
import threading
import time

app = Flask(__name__)
threads = []
stop_flags = []

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/start/')
def start():
    stop_flags.append(False)
    thread = threading.Thread(target=run_loop, args=(len(stop_flags) - 1,))
    threads.append(thread)
    thread.start()
    return render_template('index.html')

@app.route('/stop/')
def stop():
    stop_flags[-1] = True
    return render_template('index.html')

def run_loop(thread_id):
    while not stop_flags[thread_id]:
        print('pStart')
        time.sleep(1)

if __name__ == '__main__':
    app.run(debug=True)
© www.soinside.com 2019 - 2024. All rights reserved.