简体   繁体   English

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

[英]How can I access a variable declared in another file in python? (Not OOP)

I'm used to object oriented programming, dependency injection, etc. That said, I'm having trouble dealing with flask, and moving some objects around that need near global access.我习惯了面向 object 的编程、依赖注入等。也就是说,我在处理 flask 以及移动一些需要接近全局访问的对象时遇到了麻烦。 I have my routes segregated to a file called WebServer.py .我将路由隔离到一个名为WebServer.py的文件中。 I have a Main.py which serves as the entry point for the application.我有一个Main.py作为应用程序的入口点。

Main.py:主要.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:网络服务器.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 is not accessible in the index route, even if I note that it's global. x在索引路由中不可访问,即使我注意到它是全局的。

I have little experience with global variables, but I thought this would work.我对全局变量没有什么经验,但我认为这会奏效。 Does anyone know how I can make objects instantiated in Main.py accessible to WebServer.py ?有谁知道如何使WebServer.py可以访问Main.py中实例化的对象?

Circular dependencies are bad.循环依赖是不好的。 Your main should pass x as a parameter to your WebServer code rather than having WebServer import main to get it for itself.您的main应该将x作为参数传递给您的WebServer代码,而不是让WebServer import main自己获取它。

Python's notion of "global" really means "module level" - there's NO process-wide global namespace, and the goal of the global keyword is only to allow rebinding of module-level variables from within a function (which is still considered bad practice unless there's really no other solution, which is rarely the case). Python 的“全局”概念实际上意味着“模块级”——没有进程范围的全局命名空间, global关键字的目标只是允许从 function 中重新绑定模块级变量(这仍然被认为是不好的做法,除非真的没有其他解决方案,这种情况很少见)。

Also, you should particularily not use globals (I mean mutable globals) in a wsgi app - those apps are typically served (on production) as long-running processes in a multi-process pool, and any of the processes (usually the first inactive one) will serve a given request, so your mutable global state 1/ will affect all requets served by this process and 2/ will not be shared between different processes.此外,您尤其不应该在 wsgi 应用程序中使用全局变量(我的意思是可变全局变量)——这些应用程序通常作为多进程池中的长期运行进程提供(在生产中),并且任何进程(通常是第一个非活动的一)将服务于给定的请求,因此您的可变全局 state 1/ 将影响此进程服务的所有请求,并且 2/ 不会在不同进程之间共享。 So if you want to share state between processes, you use either sessions (for volatile data) or a proper database (for peristant data).因此,如果您想在进程之间共享 state,您可以使用会话(用于易失性数据)或适当的数据库(用于永久数据)。

wrt/ globals, as a general rule, you can usually avoid them with plain simple well known programming features: functions arguments, functions return values, and (if you have state to share between function calls that are not directly adjacents) classes. wrt / globals,作为一般规则,您通常可以使用简单的众所周知的编程功能来避免它们:函数 arguments、函数返回值和(如果您有 state 在 ZC1C425268E68385D1AB5074C17A94 类之间共享)调用不直接相邻。

Now if your variable is some readonly configuration variable (which is ok - there's no issue with this), the proper solution in your case here is to create a distinct config module and import it where needed, ie现在,如果您的变量是一些只读配置变量(没关系 - 这没有问题),那么在您的情况下,正确的解决方案是创建一个不同的配置模块并在需要的地方导入它,即

config.py:配置文件:

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

webserver.py网络服务器.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)

You want to import the x variable from the Main module.您想从Main模块导入x变量。

from Main import x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM