Reputation: 71
I have problems with the integration of a Flask
app served by a wsgiref.simple_server
in a Desktop app.
Our problem is that we have to start and stop the server when the user enter in a special software area that show the app via CEF browser.
All works well except when we have to stop and start the app.
One strange thing happen with a code like this:
import os
import time
import threading
from wsgiref.simple_server import make_server
from flask import Flask
def start(host='127.0.0.1', port=5000, app=None):
global SERVER, THREAD
SERVER = make_server(host, port, app)
SERVER.timeout = 1
threading.Thread(target=SERVER.serve_forever, daemon=True).start()
def stop():
global SERVER
SERVER.shutdown()
def get_app():
APP = Flask(__name__)
@APP.route("/")
def hello():
return "Hello World!"
return APP
if __name__ == '__main__':
print("First start", flush=True)
start("0.0.0.0", 5000, get_app())
time.sleep(10)
print("Start stop procedure", flush=True)
stop()
print("Stop", flush=True)
print("Second start", flush=True)
start("0.0.0.0", 5000, get_app())
time.sleep(10)
print("Start stop procedure", flush=True)
stop()
print("Stop", flush=True)
The very strange is that I need a request before the server understand that have to shutdown
$ python test.py
First start
127.0.0.1 - - [29/Oct/2018 17:04:36] "GET / HTTP/1.1" 200 12
Start stop procedure
127.0.0.1 - - [29/Oct/2018 17:04:46] "GET / HTTP/1.1" 200 12 # the unwanted request
Stop
Second start
127.0.0.1 - - [29/Oct/2018 17:04:56] "GET / HTTP/1.1" 200 12
Start stop procedure
127.0.0.1 - - [29/Oct/2018 17:05:01] "GET / HTTP/1.1" 200 12# the unwanted request
Stop
I can't have control on that. This doesn't happen with custom made wsgi app.
Is there a proper way to stop and start a Flask app? All solution on the net seem to not work
Upvotes: 0
Views: 908
Reputation: 1040
I suspect we need to use the poll_interval param for the serve_forever function.
This solution seems to work for me
import time
import threading
from wsgiref.simple_server import make_server
from flask import Flask
def get_app():
APP = Flask(__name__)
@APP.route("/")
def hello():
return "Hello World!"
return APP
class WsgiRefServer(threading.Thread):
def __init__(self, wsgi_app, host='127.0.0.1', port=5000):
super().__init__()
self._server = make_server(host, port, wsgi_app)
def run(self):
self._server.serve_forever(poll_interval=0.5)
def stop(self):
self._server.shutdown()
self.join()
if __name__ == '__main__':
http_thread = WsgiRefServer(get_app())
http_thread.start()
time.sleep(10)
http_thread.stop()
Upvotes: 1