Flask reloader and multiprocessing

Viewed 841

I have the following issue with reloading a Flask application on Windows when multiprocessing is involved.

I have created a small example to demonstrate the problem I am facing.

from flask import Flask
from werkzeug import run_simple, _reloader
import multiprocessing as mp
import os
import time


def worker_function(app_id):
    while True:
        time.sleep(2)
        # print(f'Message from {app_id}: {message}')


class MyFlask(Flask):
    def __init__(self, name):
        super().__init__(name)
        print(f'Initialising Flask app {id(self)}')

        with open('./test.txt', 'r') as f:
            self.message = f.readlines()[0]

        self.worker_process = None
        self.is_runing_from_reloader = os.environ.get("WERKZEUG_RUN_MAIN") == "true"

    def make_workers(self):
        self.worker_process = mp.Process(target=worker_function, args=(id(self),))
        self.worker_process.start()


app = MyFlask(__name__)


@app.route('/')
def message():
    return f'Running from reloader: {app.is_runing_from_reloader}. {app.message}'


if __name__ == "__main__":
    mp.freeze_support()
    print('Running main...')
    app.make_workers()
    run_simple(hostname='0.0.0.0', port=5000, application=app, use_reloader=True, extra_files=['./test.txt'])

The problem is that when I make changes to test.txt, Flask picks up that there are changes, but reloading the app is stuck. Everything works perfectly as long as the worker_process does not start.

So, I know it has something to do with the worker process but I cannot figure out what.

0 Answers
Related