1
在此Flask應用中,頁面每2秒調用check()
,並將當前app.config['count']
打印到標準輸出。還有一個按鈕,會產生一個進程,並添加一個到全局計數 - 當從相同的函數內檢查時,它可以正常工作,但是當check()
嘗試時,它始終停留在0.從Process()設置時,全局變量保存不正確()
有誰知道什麼問題這裏? do_adding_stuff()
中的睡眠只是一個佔位符,用於添加計數之前要做的其他事情。
from flask import Flask, redirect, url_for
from time import sleep
from multiprocessing import Process
app = Flask(__name__)
app.config['count'] = 0
def do_adding_stuff():
sleep(4)
print 'previous count: ' + str(app.config['count'])
app.config['count'] =+ 1
print 'new count: ' + str(app.config['count'])
@app.route('/')
def index():
return """
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script>
var a = setInterval(function(){
$.post("/check", {"dummy": "data"})
}, 2000)
</script>
<form method="post" action="add">
<input type="submit" value="add 1 to count">
</form>
"""
@app.route('/add', methods=['POST'])
def add():
proc = Process(target=do_adding_stuff)
proc.start()
return redirect(url_for('index'))
@app.route('/check', methods=['POST'])
def check():
print('check(): ' + str(app.config['count']))
return ''
if __name__ == '__main__':
app.run(debug=True)
輸出:
check(): 0
check(): 0
check(): 0
check(): 0
previous count: 0
new count: 1
check(): 0
check(): 0