我正在尝试将数据从流程传递到烧瓶流程。 试图在烧瓶过程中使用全局变量,但我不能在进程之间传输数据。也尝试烧瓶作为线程但它没有反应。 代码:
from flask import Flask
from multiprocessing import Process, Queue
import time
globalvar=0
app = Flask(__name__)
@app.route('/')
def index():
return "globvar in index="+str(globalvar) # I want to return globvar
def multiprocess(q):
#global globalvar tried but same result
i=0
while 1: # for keep fresh value of i
i+=1
variable = i % 10
print "i in multiprocess=" + str(i)
q.put(variable)
time.sleep(1)
def flaskserver():
app.run(debug=True, host='127.0.0.1', port=7654,use_reloader=False)
if(__name__=='__main__'):
q = Queue()
p1 = Process(target=flaskserver)
p2 = Process(target=multiprocess, args=(q,))
p1.start()
p2.start()
while 1:
globalvar = q.get()
print "globalvar in main=" + str(globalvar)
time.sleep(3)
CONSOLE OUTPUT:
/usr/bin/python /Users/macbook/Desktop/python/stack-flask-multi.py i in multiprocess=1 globalvar in main=1 * Running on http://127.0.0.1:7654/ (Press CTRL+C to quit) i in multiprocess=2 i in multiprocess=3 i in multiprocess=4 globalvar in main=2 i in multiprocess=5 i in multiprocess=6 i in multiprocess=7 globalvar in main=3 i in multiprocess=8 i in multiprocess=9 i in multiprocess=10 globalvar in main=4
浏览器中的请求页面:
127.0.0.1 - - [22/Mar/2018 01:28:00] "GET / HTTP/1.1" 200 -
在浏览器中返回 - > index = 0中的globvar
答案 0 :(得分:1)
我没有看到你的问题...... 这看起来像回答了你的问题:
from flask import Flask
from multiprocessing import Process, Queue
import time
globalvar=0
app = Flask(__name__)
@app.route('/')
def index():
return "globvar in index=" + str(q.get()) # Now, it will return a value other than 0!
def multiprocess(q):
# global globalvar tried but same result
i = 0
while 1: # for keep fresh value of i
i += 1
variable = i % 10
print "i in multiprocess=" + str(i)
q.put(variable)
time.sleep(0.1)
def flaskserver():
app.run(debug=True, host='127.0.0.1', port=7654, use_reloader=False)
if (__name__ == '__main__'):
q = Queue()
p1 = Process(target=flaskserver)
p2 = Process(target=multiprocess, args=(q,))
p1.start()
p2.start()
while 1:
globalvar = q.get()
print "globalvar in main=" + str(globalvar)
time.sleep(0.1)