I have a flask app which I need to start and then shut down within the same process and repeat this multiple times. I am using gevents in my application so I'm using gevents.pywsgi
as my WSGI server. Now I'm trying to gracefully shutdown the server so I can restart it in the same process after I do a few other things.
So the following code creates a basic flask app, which when receives a POST request with any valid data on /hit endpoint populates the data field. A greenlet is running in parallel with this app and when it sees that the data field is populated, it shuts down the server.
def func():
global data
data = None
app = Flask(__name__)
@app.route('/hit', methods=['POST'])
def hit():
global data
data = request.json
if data is not None:
return "Input Recieved, Server closed "
else:
return "Invalid Input, Try again"
def shutdown_server(_server):
global data
while data is None:
sleep(0.5)
_server.stop()
_server.close()
server = WSGIServer(('0.0.0.0',5100), app)
start = spawn(server.start)
stop = spawn(shutdown_server, request, server)
joinall([start, stop])
return True
Now this code is running fine if I run the server once, but if I try to run the server again within the same process it throws the following error:
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 766, in gevent._greenlet.Greenlet.run
File "/home/batman/Documents/genisys/lib/python3.6/site-packages/gevent/baseserver.py", line 308, in start
self.start_accepting()
File "/home/batman/Documents/genisys/lib/python3.6/site-packages/gevent/baseserver.py", line 160, in start_accepting
self._watcher = self.loop.io(self.socket.fileno(), 1)
AttributeError: 'WSGIServer' object has no attribute 'socket'
I'm not sure if this is even possible, or if I have to run the server in a separate process if I want to run it multiple times. Can anybody tell me why I'm facing this error and is there a better and cleaner way to shutdown the server so I don't face this error?
EDIT : I give IP and port as arguments to func, so I have tried call func with a different port multiple times and with the same port multiple times, I still get the same error.