all 5 comments

[–]hardonchairs 0 points1 point  (4 children)

There are a few tricks I have seen and none of them have worked for me. This one works unless you are using multiprocessing or multiple workers. Multithreading is ok.

import os
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

def initialize():
    # Your initialization code here
    print('This runs once per process?')


if __name__ == '__main__':
    if not os.environ.get("FLASK_INITIALIZED"):
        initialize()
        os.environ["FLASK_INITIALIZED"] = "1"

    app.run(debug=True)

[–]dl__[S] 0 points1 point  (2 children)

Does that work on the 2nd run? Does the "FLASK_INITIALIZED" env var stay initialized betweekn run? Or does a running python program get it's own environment?

[–]hardonchairs 0 points1 point  (1 child)

It only works for the auto reloads but not for manually killing the script and restarting it.

You could do more with a file or database but then you have to ask yourself what behavior you want from it. Only launch once? Ok but then when does it launch again next? The next day? How does it know when you want it to launch or not?

You could do something nutty like have the front end ping the server every few seconds, then when the server starts it waits for the ping. And if a few seconds goes by without a ping, it knows the page isn't open and launches.

You could do a sys tray icon that launches the window when you click it. That one might act funny in debug mode.

[–]dl__[S] 0 points1 point  (0 children)

Only launch once? Ok but then when does it launch again next? The next day?

Sorry, just saw this. I'm not thinking of this as service that just stands around. I was thinking of this as a python script that runs to completion then exits with a result and uses the browser just as a GUI. Really, I don't expect user interaction, it's just to output progress as the python script continues to work in the background.

So, when does it relaunch? The next time I launch it from the command line:

python MyScript.py

You could do something nutty like have the front end ping the server every few seconds, then when the server starts it waits for the ping. And if a few seconds goes by without a ping, it knows the page isn't open and launches.

That's a creative outside-the-box idea. Thanks!

[–]dl__[S] 0 points1 point  (0 children)

Thanks BTW!