Search code examples
python-3.xflaskwerkzeug

Make Flask restart only when a specific file is edited


I have a website set up with Flask (Following the flask mega tutorial). I have my views.py which I edit as I develop. In the same directory I have a temp.py which is edited programmatically.

Right now I have my server set to DEBUG so that every time I edit views.py, the server restarts. My problem is, every time my program edits temp.py, the server also restarts and this is causing a lot of things to break. Is there any way for me to make flask ignore temp.py and only look at views.py when deciding to restart?


Solution

  • Suppress Flask server restarts in debug mode for all source file changes

    Excerpt from Flask documentation:

    Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke run() with debug=True and use_reloader=False.

    Following will make sure server will not restart in case if any of the source files are changed:

    app.run(debug=True, use_reloader=False)
    

    Suppress Flask server restarts in debug mode for some source file changes

    For your particular scenario, where you want to suppress server restart only for some of the source files, I'd use dynamic module loading. The easiest approach to achieve this is to remove particular module from imports and to use __import__ function instead.

    Example code - call the function modules.temp.ololo(args):

    try:
        # Dynamic import
        module = __import__('modules.temp')
        try:
            # Execute function
            res = getattr(module, 'ololo')(args)
        except AttributeError:
            flask.current_app.logger.error('Function not found')
    except ImportError:
        flask.current_app.logger.error('Module not found')
    

    Move your temp.py into a module, dedicated for dynamic loading, and adjust your code to use the resources from there in a similar way.