Why does running the Flask dev server run itself twice?

I’m using Flask for developing a website and while in development I run flask using the following file:

#!/usr/bin/env python
from datetime import datetime
from 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 I start the server, or when it auto-restarts because files have been updated, it always shows the print line twice:

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

Answer:

The Werkzeug reloader spawns a child process so that it can restart that process each time your code changes. Werkzeug is the library that supplies Flask with the development server when you call app.run().

See the restart_with_reloader() function code; your script is run again with subprocess.call()

If you set use_reloader to False you’ll see the behaviour go away, but then you also lose the reloading functionality:

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

You can disable the reloader when using the flask run command too:

FLASK_DEBUG=1 flask run --no-reload

You can look for the WERKZEUG_RUN_MAIN environment variable if you wanted to detect when you are in the reloading child process:

import os
if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
    print '################### Restarting @ {} ###################'.format(
        datetime.utcnow())

However, if you need to set up module globals, then you should instead use the @app.before_first_request decorator on a function and have that function set up such globals. It’ll be called just once after every reload when the first request comes in:

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

Do take into account that if you run this in a full-scale WSGI server that uses forking or new subprocesses to handle requests, that before_first_request handlers may be invoked for each new subprocess.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值