我是python的新手,所以请不要对我太客气。我相信有更好的方法来实现我正在努力实现的目标。这是一个学习的过程。
我有一个类,我在其中定义了一个变量,然后在稍后的代码中修改它的设置(我想让它根据变量的条件做一些事情,并一直在后台运行)。
当我在函数中执行此操作时,它会按预期工作。但是,当我在Flask的路由函数中执行此操作时,变量会在线程启动时的设置方式和路由函数的更改方式之间摇摆。它每次在循环中都会这样做。
我不明白它为什么这样做,但我一直无法修复它,并正在寻求一些帮助。任何帮助都将不胜感激。
代码如下:
#import time for time functionality
import time
##import flask
from flask import Flask, render_template, request, redirect, Response, json
app = Flask(__name__)
#import threading to run processes in background as threads
import threading
class param:
status = {
'VariableToWatch' : 'Condition-1'
}
class myThread (threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.signal = True
def run(self):
while self.signal:
print 'In the myThread Loop. VariableToWatch is', param.status['VariableToWatch']
if param.status['VariableToWatch'] == 'Run':
print 'VariableToWatch is', param.status['VariableToWatch']
if param.status['VariableToWatch'] != 'Run':
print 'VariableToWatch is', param.status['VariableToWatch']
time.sleep(1)
# main web page
@app.route('/', methods=['GET', 'POST'])
def index():
print 'At the index function'
param.status['VariableToWatch'] = 'Condition-2'
raw_input('Waiting..... Press ENTER to continue')
if __name__ == "__main__":
#Launch the heating thread
ThreadID_7 = myThread(7, "HeatMe")
ThreadID_7.start()
app.run(debug=True, host='0.0.0.0')
server = WSGIServer(("", 5000), app)
server.serve_forever()在用浏览器点击它之前,输出如下所示:
In the myThread Loop. VariableToWatch is Condition-1
VariableToWatch is Condition-1
In the myThread Loop. VariableToWatch is Condition-1
VariableToWatch is Condition-1
In the myThread Loop. VariableToWatch is Condition-1
VariableToWatch is Condition-1在你用浏览器点击它之后,路由的函数被调用:
VariableToWatch is Condition-1
In the myThread Loop. VariableToWatch is Condition-2
VariableToWatch is Condition-2
In the myThread Loop. VariableToWatch is Condition-1
VariableToWatch is Condition-1
In the myThread Loop. VariableToWatch is Condition-2
VariableToWatch is Condition-2发布于 2016-02-29 04:17:00
WSGI可能会多次运行您的程序,创建多个正在运行的实例来服务于请求。在每次运行时,都会创建一个名为param的类。因此,您实际上可能有多个名为param的类,每个类都有自己的进程。您可以通过在打印小状态检查的相同位置执行print(id(param))来检查这一点;您可能会看到打印出不同的值。
当使用像WSGI这样的东西时,你不能在全局状态下安全地存储任何东西。您需要使用数据库,或者Flask的会话管理工具,或者其他一些网络感知解决方案来跨多个请求持久化数据。如何做到这一点取决于你希望它持久的程度(例如,你希望它持续到单个用户的会话,还是单个页面的单个视图,等等)。
https://stackoverflow.com/questions/35687616
复制相似问题