我正在构建一个Flask应用程序,它需要跨请求访问初始化的类。下面对Flask服务器的POST请求表明,全局变量ex的类型为None,尽管它在启动时被初始化并重新分配给main中的Engine类。为什么会这样
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从未被完全赋值。(其他发现此问题的人请注意)
尝试在第一次请求之前使用@flask\u app.before\u,然后创建线程。如果您想了解更多详细信息,我将留下此链接:Global variable is None instead of instance - Python
我在添加缺少的导入、设置rd_信息并将端口更改为5000(因为在许多系统中低于1024的端口是特权端口)后运行了您的代码
然后
引起
加上卷曲侧的烧瓶/Werkzeug调试信息。考虑到路线中缺少返回,我预计会出现打字错误。不过,这证明线程正在运行
这是在Ubuntu18.04和Python3.6.9上实现的
相关问题 更多 >
编程相关推荐