Skip to content Skip to sidebar Skip to footer

Starting And Stopping Flask On Demand

I am writing an application, which can expose a simple RPC interface implemented with flask. However I want it to be possible to activate and deactivate that interface. Also it sho

Solution 1:

Answering my own question in case this ever happens again to anyone.

The first solution involved switching from flask to klein. Klein is basically flask with less features, but running on top of the twisted reactor. This way the integration is very simple. Basically it works like this:

from klein import Klein
from twisted.internet import reactor

app = Klein()

@app.route('/')
def home(request):
    return 'Some website'

endpoint = serverFromString(reactor, endpoint_string)
endpoint.listen(Site(app.resource()))

reactor.run()

Now all the twisted tools can be used to start and stop the server as needed.

The second solution I switched to further down the road was to get rid of HTTP as a transport protocol. I switched to JSONRPC on top of twisted's LineReceiver protocol. This way everything got even simpler and I didn't use any of the HTTP stuff anyway.


Solution 2:

This is a terrible, horrendous hack that nobody should ever use for any purpose whatsoever... except maybe if you're trying to write an integration test suite. There are probably better approaches - but if you're trying to do exactly what the question is asking, here goes...

import sys
from socketserver import BaseSocketServer

# implementing the shutdown() method above
def shutdown(self):
    for frame in sys._current_frames().values():
        while frame is not None:
            if 'srv' in frame.f_locals and isinstance(frame.f_locals['srv'], BaseSocketServer):
                frame.f_locals['srv'].shutdown()
                break
        else:
            continue
        break
    self.flask_thread.join()

Post a Comment for "Starting And Stopping Flask On Demand"