Run Code Alongside A Flask Application
Solution 1:
It's possible, and sometime convenient, to run Flask in a thread off of a foreground application. There is a trick, a big pitfall, and a constraint.
The constraint is that this is something you'll want to do in a "safe" environment (e.g. on your laptop to server a local browser, or on your home intranet), as it involves running the development server, which is something you don't want to be doing in a hostile environment. You also can't use automatic page reloading (but you can enable debug).
The pitfall is that if the UI is sharing any non-trivial state (including dicts) with the foreground app, you'll need to use a shared threading.Lock() to guard access such that only one thread at a time is reading or writing data.
The trick is to inject a reference to shared state into the app's config after you create it but before you start it, doing something like:
def webserver(state):
    app.config['STATE'] = state
    # If running on, say, a Raspberry Pi, use 0.0.0.0 so that
    # you can connect to the web server from your intranet.
    app.run(host='0.0.0.0', use_reloader=False, debug=True)
def main():
    state = SharedState()
    web_thread = threading.Thread(target=webserver, args=(state,))
    web_thread.start()
    state.set('counter' 0)
    while True:
        # Do whatever you want in the foreground thread
        state.set('counter', state.get('counter') + 1)
class SharedState():
    def __init__(self):
        self.lock = threading.Lock()
        self.state = dict()
    def get(self, key):
        with self.lock:
            return self.state.get(key)
    def set(self, key, value):
        with self.lock:
            self.state[key] = value
Then, from within Flask view functions, do something like
@app.route('/')
def home():
    state = app.config['STATE']
    counter = state.get(counter)
    return render_template("index.html", counter=counter)
Post a Comment for "Run Code Alongside A Flask Application"