Search code examples
flaskwerkzeug

Is it possible to have Flask/Werkzeug's auto reloader respect the -O optimisation flag


Basically, I have a small portion of my Flask-based application which spawns a background process to do some work. In a production environment I simply want to suprocess.Popen and 'ignore' what happens to that subprocess. However during development I want to use check_output instead so that in case something does go wrong I have a better chance of catching it.

In order to determine whether or not to use check_output I just wrap it in a if __debug__, which more or less translates into:

def spawn_process():
    if __debug__:
        subprocess.check_output(args, stderr=subprocess.STDOUT)
    else:
        subprocess.Popen(args)

I was under the impression that by doing this I could simply use the -O Python flag to get the alternate behavior during development -- in production I was planning on using mod_wsgi's WSGIPythonOptimize directive for the same effect. However it appears that Flask/Werkzeug's auto reloader ignores the Python flags when it spawns its own subprocess. A simple print __debug__ in the debugger showed what it was indeed set to True and sys.flags was all zero.

So my question is: is there any way to force Flask/Werkzeug's auto reloader to respect the flags initially passed to Python?

Disabling auto-reload does mean the -O flag gets used, but doing that is a small inconvenience I'd rather not deal with it there's a better way.


Solution

  • I don't believe you can have the autoreloader respect the -O flag. You could however check the debug flag in your application to decide how to spawn you subprocess:

    from flask import current_app
    
    def spawn_process():
        if current_app.debug:
            subprocess.check_output(args, stderr=subprocess.STDOUT)
        else:
            subprocess.Popen(args)