我正在构建一个Flask应用程序,该应用程序需要跨请求访问初始化的类。下面对Flask服务器的POST请求说,尽管全局变量ex在启动时已初始化并重新分配给main中的Engine类,但其类型为None 。为什么是这样?
ex = None #Storing the executable so that it can be accessed
flask_app = Flask(__name__)
flask_app.debug = True
@flask_app.route('/reach_engine', methods = ['POST'])
def result():
global ex
print(ex.txt) #Prints type error, saying that ex is of type None (this is the problem)
class Engine:
def __init__(self):
super(Engine, self).__init__()
self.txt = 'The real Engine'
def startApp():
global ex
ex = Engine()
if __name__ == '__main__':
#Start a thread that will run the main app
t = threading.Thread(target=startApp)
t.daemon = True
t.start()
# Start the flask app
print(rd_info + "Intializing Flask application")
flask_app.run('0.0.0.0', '1000', debug=True,
threaded=True, use_reloader=False)
现在已经解决了。在原始代码中,引擎初始化中存在故意的for循环,从而导致全局变量ex从未完全分配。(其他人请注意)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句