How to I Close Down a Python Server Built Using Flask

How to stop flask application without using ctrl-c

If you are just running the server on your desktop, you can expose an endpoint to kill the server (read more at Shutdown The Simple Server):

from flask import request
def shutdown_server():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()

@app.get('/shutdown')
def shutdown():
shutdown_server()
return 'Server shutting down...'

Here is another approach that is more contained:

from multiprocessing import Process

server = Process(target=app.run)
server.start()
# ...
server.terminate()
server.join()

Let me know if this helps.

How to move out of app.run() in flask API Python

I have resolved the issue by starting the API server in separate thread so that Ui keeps on working. Then I am shutting down the API server using shutdown api

run = True


def start_api_server():
while run:
start_local_server()

time.sleep(1)
print("SERVER HAS STOPPED")

@pyqtSlot()
def on_click_start_btn(self):
Thread(target=start_api_server).start()

Above is the code to start the server on button click. Below is how I am shutting it down:

@pyqtSlot()
def on_click_stop_btn(self):
global run
print("STOPPING SERVER")
run = False
try:
x = requests.get("http://localhost:80/api/shutdown")
rdata = x.text
rdata = json.loads(rdata)
if rdata['status']:
print("Server shutting down")
print(rdata)

except Exception as e:
print(e)

Above code calls a shutdown API which terminate the flask api server. Below is the code for it:

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('/api/shutdown')
def shutdown():
shutdown_server()
return 'Server shutting down...'

How do I terminate a flask app that's running as a service?

I recommend you use http://supervisord.org/. Actually not work in Windows, but with Cygwin you can run supervisor as in Linux, including run as service.

For install Supervisord: https://stackoverflow.com/a/18032347/3380763

After install you must configure the app, here an example: http://flaviusim.com/blog/Deploying-Flask-with-nginx-uWSGI-and-Supervisor/ (Is not necessary that you use Nginx with the Supervisor's configuration is enough)



Related Topics



Leave a reply



Submit