我正在使用Flask作为REST端点,它将一个应用程序请求添加到队列中。然后,队列由第二个线程使用。
server.py
def get_application():
global app
app.debug = True
app.queue = client.Agent()
app.queue.start()
return app
@app.route("/api/v1/test/", methods=["POST"])
def test():
if request.method == "POST":
try:
#add the request parameters to queue
app.queue.add_to_queue(req)
except Exception:
return "All the parameters must be provided" , 400
return "", 200
return "Resource not found",404
client.py
class Agent(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.active = True
self.queue = Queue.Queue(0)
def run(self):
while self.active:
req = self.queue.get()
#do something
def add_to_queue(self,request):
self.queue.put(request)
烧瓶中是否有关闭事件处理程序,以便在烧瓶应用程序关闭时(例如重启apache服务时)可以干净地关闭使用者线程?
答案 0 :(得分:17)
没有app.stop()如果你正在寻找它,但是使用模块atexit
你可以做类似的事情:
https://docs.python.org/2/library/atexit.html
考虑一下:
import atexit
#defining function to run on shutdown
def close_running_threads():
for thread in the_threads:
thread.join()
print "Threads complete, ready to finish"
#Register the function to be called on exit
atexit.register(close_running_threads)
#start your process
app.run()
另外值得注意的是,如果使用Ctrl-C强行关闭服务器,则不会调用atexit
。
为此,还有另一个模块 - signal
。
答案 1 :(得分:1)
from flask import request
BASE_URL = "http://127.0.0.1:5000"
SHUTDOWN = "/shutdown"
def shutdown_server():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
@app.route(SHUTDOWN, methods=['POST'])
def shutdown():
shutdown_server()
return 'Server shutting down...'
这里似乎提到了一种方法:- http://web.archive.org/web/20190706125149/http://flask.pocoo.org/snippets/67