我习惯于面向对象编程、依赖项注入等。也就是说,我在处理flask和移动一些需要接近全局访问的对象时遇到了问题。我将路由隔离到名为WebServer.py
的文件。我有一个Main.py
作为应用程序的入口点
Main.py:
x = "test"
import WebServer
# WSGI entry point
def main():
return WebServer.app
if __name__ == '__main__':
from DebugWebServer import DebugWebServer
server = DebugWebServer()
server.run(WebServer.app)
WebServer.py:
from flask import Flask
from flask import render_template
from flask import Response
app = Flask(__name__)
@app.route('/')
def index():
global x
print(x)
return render_template('index.html')
x
在索引路由中不可访问,即使我注意到它是全局的
我对全局变量几乎没有经验,但我认为这是可行的。有人知道我如何使Main.py
中实例化的对象可供WebServer.py
访问吗
Python的“全局”概念实际上意味着“模块级”-没有进程范围的全局名称空间,
global
关键字的目标只是允许从函数中重新绑定模块级变量(这仍然被认为是错误的做法,除非真的没有其他解决方案,这种情况很少发生)此外,您尤其不应该在wsgi应用程序中使用全局变量(我指可变全局变量)——这些应用程序通常作为多进程池中的长时间运行进程提供(在生产中),并且任何进程(通常是第一个非活动进程)都将为给定的请求提供服务,因此,您的可变全局状态1/将影响此流程提供的所有需求,2/不会在不同流程之间共享。所以,如果您想在进程之间共享状态,可以使用会话(用于易失性数据)或适当的数据库(用于peristant数据)
wrt/globals,作为一般规则,您通常可以使用简单的众所周知的编程特性来避免它们:函数参数、函数返回值和(如果您在非直接相邻的函数调用之间有状态共享)类
现在,如果您的变量是某个只读配置变量(这是可以的-这没有问题),那么在您的情况下,正确的解决方案是创建一个独特的配置模块,并在需要时导入它,即
config.py:
webserver.py
main.py
循环依赖是不好的。你的
main
应该将x
作为参数传递给你的WebServer
代码,而不是让WebServer
导入main
来自行获取它您想从
Main
模块导入x
变量相关问题 更多 >
编程相关推荐