python - Why does running the Flask dev server run itself twice? -


i'm using flask developing website , while in development run flask using following file:

#!/usr/bin/env python datetime import datetime app import app import config  if __name__ == '__main__':     print '################### restarting @', datetime.utcnow(), '###################'     app.run(port=4004, debug=config.debug, host='0.0.0.0') 

when start server, or when auto-restarts because files have been updated, shows print line twice:

################### restarting @ 2014-08-26 10:51:49.167062 ################### ################### restarting @ 2014-08-26 10:51:49.607096 ################### 

although not problem (everything rest works expected), wonder why behaves this? ideas?

the werkzeug reloader spawns child process can restart process each time code changes. werkzeug library supplies flask development server when call app.run().

see restart_with_reloader() function code; script run again subprocess.call().

if set use_reloader false you'll see behaviour go away, lose reloading functionality:

app.run(port=4004, debug=config.debug, host='0.0.0.0', use_reloader=false) 

you can werkzeug_run_main environment variable if wanted detect when in reloading child process:

if __name__ == '__main__':     import os     if os.environ.get('werkzeug_run_main') == 'true':         print '################### restarting @ {} ###################'.format(             datetime.utcnow())     app.run(port=4004, debug=config.debug, host='0.0.0.0') 

however, if need set module globals, should instead use @app.before_first_request decorator on function , have function set such globals. it'll called once after every reload when first request comes in:

@app.before_first_request def before_first_request():     print '########### restarted, first request @ {} ############'.format(         datetime.utcnow()) 

do take account if run in full-scale wsgi server uses forking or new subprocesses handle requests, before_first_request handlers may invoked each new subprocess.


Comments