Flask Web服务器应用在Windows Python程序中无法在程序退出时关闭。

huangapple go评论64阅读模式
英文:

Flask Web server App on Window Python program is not able to shutdown on program exist

问题

以下是代码的翻译部分:

# 导入必要的模块
from flask import Flask, request
from multiprocessing import Process
import os

# 一些常量
OUTPUT_EMPTY_LIMIT = 3
DEFAULT_PORT = 9090
SHUTDOWN = False
EXIT_CHARS = "Qq\x11\x18"  # 'Q', 'q', Ctrl-Q, ESC

# 创建Flask应用
app = Flask(__name__)

# 关闭应用的函数
def shutdown_app():
    global SHUTDOWN
    SHUTDOWN = True

# 在请求处理之前检查是否需要关闭应用
@app.before_request
def before_request():
    if SHUTDOWN:
        return 'Shutting down...'

# 运行Flask应用的函数
def run_app(port, host, debug, threaded):
    app.run(port=port, host=host, debug=debug, threaded=threaded)

# 定义根路由
@app.route("/")
def app_help():
    return "Hello, World from help!"

# 定义一个路由,计算数字的平方
@app.route("/square/<int:number>")
def square(number):
    return str(number ** 2)

# 关闭应用的路由
@app.route("/stop")
def stop():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the werkzeug Server')
    func()
    return 'Server shutting down...'
    exit(0)

if __name__ == "__main__":
    port = 5000
    host = '0.0.0.0'
    debug = False
    threaded = True
    process = Process(target=run_app, args=(port, host, debug, threaded))
    process.start()

    while True:
        ch = input("Enter 'Q' to stop server and exit: ")
        if (ch == 'Q'):
            break

    shutdown_app()
    process.terminate()
    print("Exiting the app")
    os._exit(0)

这是你提供的Python Flask应用代码的翻译部分,没有包括代码外的其他信息。如果你有关于这段代码的问题或需要进一步的帮助,请随时提问。

英文:

I have python version 3.9, I am using the default development web server that is provided by the flask on windows OS (laptop). I need to run the app on Windows machine, and it should be able to start and stop the app on demand.

Here is what I tried so far. when I run the application either in VS code, I need to force stop the app, If running in the command windows I have to kill the python app from task manager.
With the following code changes I can exit the app by sending the SIGTERM to proess itself, as both the Flask, and simplehttpserver do not provide an API for exiting the process.

from flask import Flask, request, g, make_response
import queue
import time
import os
from threading import Thread
import signal
import ctypes
from multiprocessing import Process
import sys
OUTPUT_EMPTY_LIMIT = 3 
DEFAULT_PORT = 9090
SHUTDOWN    = False
EXIT_CHARS  = &quot;Qq\x11\x18&quot;      # &#39;Q&#39;, &#39;q&#39;, Ctrl-Q, ESC
print(&quot;Name = {}&quot;.format(__name__))
app = Flask(__name__)
def shutdown_app():
global SHUTDOWN
SHUTDOWN = True
@app.before_request
def before_request():
if SHUTDOWN:
return &#39;Shutting down...&#39;
def run_app(port, host, debug, threaded):
app.run(port=port, host=host, debug=debug, threaded=threaded)
@app.route(&quot;/&quot;)
def app_help():
return &quot;Hello, World from help!&quot;
@app.route(&quot;/square/&lt;int:number&gt;&quot;)
def square(number):
return str(number**2)
# This doesnt kill the app as well.
@app.route(&quot;/stop&quot;)
def stop():
func = request.environ.get(&#39;werkzeug.server.shutdown&#39;)
if func is None:
raise RuntimeError(&#39;Not running with the werkzeug Server&#39;)
func()
return &#39;Server shutting down...&#39;
exit(0)
if __name__ == &quot;__main__&quot;:
port = 5000
host = &#39;0.0.0.0&#39;
debug = False
threaded = True   
process = Process(target=run_app, args=(port, host, debug, threaded))
process.start()
while True:
ch = input(&quot;Enter &#39;Q&#39; to stop server and exit: &quot;)
if (ch == &#39;Q&#39;):
break
shutdown_app()
process.terminate()
#process.kill()
#process.join()
print(&quot;Exiting the app&quot;)
# os.kill(os.getpid(), signal.SIGINT)
os._exit(0)

I am new to Python and have tried both google search and chatGPT to find a way to shutdown Flask App and the web server that is started on a windows operating system.
I have also tried the other answeres on the stack overflow 15562446

I also tried the link Shutdown The Simple Server

答案1

得分: 1

I've found while testing that werkzeug.server.shutdown does nothing, and it needs to be shutdown using sys.exit(0) on my windows machine.
In your code a value is returned before the exit() is run - therefore it does not shut down. One way to do what you want is using deferred callbacks.

from flask import after_this_request 

@app.get('/stop')
def shutdown():
    @after_this_request
    def response_processor(response):
        @response.call_on_close
        def shutdown():
            import sys
            sys.exit("Stop API Called")
        return response
    return 'Server shutting down...', 200
英文:

I've found while testing that werkzeug.server.shutdown does nothing, and it needs to be shutdown using sys.exit(0) on my windows machine.
In your code a value is returned before the exit() is run - therefore it does not shut down. One way to do what you want is using deferred callbacks.

from flask import after_this_request 
@app.get(&#39;/stop&#39;)
def shutdown():
@after_this_request
def response_processor(response):
@response.call_on_close
def shutdown():
import sys
sys.exit(&quot;Stop API Called&quot;)
return response
return &#39;Server shutting down...&#39;,200

huangapple
  • 本文由 发表于 2023年2月14日 08:39:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定