如何访问python中另一个文件中声明的变量?(不是OOP)

2024-09-30 08:20:19 发布

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

我习惯于面向对象编程、依赖项注入等。也就是说,我在处理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访问吗


Tags: 对象namefrompyimportappflask路由
3条回答

Python的“全局”概念实际上意味着“模块级”-没有进程范围的全局名称空间,global关键字的目标只是允许从函数中重新绑定模块级变量(这仍然被认为是错误的做法,除非真的没有其他解决方案,这种情况很少发生)

此外,您尤其不应该在wsgi应用程序中使用全局变量(我指可变全局变量)——这些应用程序通常作为多进程池中的长时间运行进程提供(在生产中),并且任何进程(通常是第一个非活动进程)都将为给定的请求提供服务,因此,您的可变全局状态1/将影响此流程提供的所有需求,2/不会在不同流程之间共享。所以,如果您想在进程之间共享状态,可以使用会话(用于易失性数据)或适当的数据库(用于peristant数据)

wrt/globals,作为一般规则,您通常可以使用简单的众所周知的编程特性来避免它们:函数参数、函数返回值和(如果您在非直接相邻的函数调用之间有状态共享)类

现在,如果您的变量是某个只读配置变量(这是可以的-这没有问题),那么在您的情况下,正确的解决方案是创建一个独特的配置模块,并在需要时导入它,即

config.py:

# naming convention: use ALL_UPPER for pseudo-constants
X = 42

webserver.py

from flask import Flask
from flask import render_template
from flask import Response

import config

app = Flask(__name__)

@app.route('/')
def index():
    print(config.X)
    return render_template('index.html')

main.py

# note that this is your module, not the WebServer.WebServer class
# following naming conventions (module names should be all_lower)
# helps avoiding this kind of confusions

import WebServer

# contrived example, just to find a use for `config.X` here
import config
print("in main, config.X = {}".format(config.X)

# WSGI entry point
def main():
    return WebServer.app

if __name__ == '__main__':
    from DebugWebServer import DebugWebServer
    server = DebugWebServer()
    server.run(WebServer.app)

循环依赖是不好的。你的main应该将x作为参数传递给你的WebServer代码,而不是让WebServer导入main来自行获取它

您想从Main模块导入x变量

from Main import x

相关问题 更多 >

    热门问题