Flask中的全局变量重置为无

2024-04-19 05:41:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个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) 

Tags: thenamedebugselfnonetrueappflask
3条回答

这个问题现在已经解决了。在原始代码中,在引擎初始化过程中有一个故意的for循环,导致全局变量ex从未被完全赋值。(其他发现此问题的人请注意)

尝试在第一次请求之前使用@flask\u app.before\u,然后创建线程。如果您想了解更多详细信息,我将留下此链接:Global variable is None instead of instance - Python

我在添加缺少的导入、设置rd_信息并将端口更改为5000(因为在许多系统中低于1024的端口是特权端口)后运行了您的代码

$ python stackoverflow.py
random-Intializing Flask application
* Serving Flask app "stackoverflow" (lazy loading)
* Environment: production
  WARNING: This is a development server. Do not use it in a production deployment.
  Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

然后

$ curl  request POST  data '' http://0.0.0.0:5000/reach_engine

引起

The real Engine
10.0.2.2 - - [10/Jul/2020 17:31:18] "POST /reach_engine HTTP/1.1" 500 -
Traceback (most recent call last):
...
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

加上卷曲侧的烧瓶/Werkzeug调试信息。考虑到路线中缺少返回,我预计会出现打字错误。不过,这证明线程正在运行

这是在Ubuntu18.04和Python3.6.9上实现的

相关问题 更多 >