在这个 Flask 应用程序中,页面check()
每 2 秒调用一次,并将当前打印app.config['count']
到标准输出。还有一个按钮可以生成一个进程并将一个添加到全局计数中——当从同一个函数内部检查时,它可以正常工作,但在check()
尝试时,它总是停留在 0。
有谁知道这里有什么问题?sleep indo_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