How can I create an application scope variable which is loaded when the django app starts, be in memory and accessible by all.
如何创建一个应用程序范围变量,该变量在django应用程序启动时加载,位于内存中并可供所有人访问。
Basically I want to reuse the variable through out the application without reloading it.
基本上我想在整个应用程序中重用变量而不重新加载它。
Thanks
谢谢
3 个解决方案
#1
7
You could add it to your settings.py
file. Or, add it to the __init__.py
file inside the app directory.
您可以将其添加到settings.py文件中。或者,将其添加到app目录中的__init__.py文件中。
#2
3
Are you referring to something like an environment variable? You could load it via init...
你指的是环境变量吗?你可以通过init加载它...
__init__.py
import os
os.environ['APP_VAR_WHATEVER'] = 'hello world!'
#3
2
Python has three levels of namespace — local (specific to the current function or class method), global (specific to the current module), and built-in. That is, Python does not really have project-wide global variables.
Python有三个级别的命名空间 - 本地(特定于当前函数或类方法),全局(特定于当前模块)和内置。也就是说,Python实际上没有项目范围的全局变量。
If it's a read-only variable you want, you could use settings.py
to define the value and import settings
from all other modules that want access to the variable.
如果它是您想要的只读变量,您可以使用settings.py来定义值,并从所有其他想要访问变量的模块中导入设置。
If it for both reading and writing, I would likely use the database backend I'm already using with Django, instead of a python variable.
如果它同时用于读写,我可能会使用我已经使用Django的数据库后端,而不是python变量。
If you could provide a more detailed description of what you're trying to achieve, perhaps we could come up with a better suited solution.
如果你能提供一个更详细的描述,你可能会想出一个更合适的解决方案。
#1
7
You could add it to your settings.py
file. Or, add it to the __init__.py
file inside the app directory.
您可以将其添加到settings.py文件中。或者,将其添加到app目录中的__init__.py文件中。
#2
3
Are you referring to something like an environment variable? You could load it via init...
你指的是环境变量吗?你可以通过init加载它...
__init__.py
import os
os.environ['APP_VAR_WHATEVER'] = 'hello world!'
#3
2
Python has three levels of namespace — local (specific to the current function or class method), global (specific to the current module), and built-in. That is, Python does not really have project-wide global variables.
Python有三个级别的命名空间 - 本地(特定于当前函数或类方法),全局(特定于当前模块)和内置。也就是说,Python实际上没有项目范围的全局变量。
If it's a read-only variable you want, you could use settings.py
to define the value and import settings
from all other modules that want access to the variable.
如果它是您想要的只读变量,您可以使用settings.py来定义值,并从所有其他想要访问变量的模块中导入设置。
If it for both reading and writing, I would likely use the database backend I'm already using with Django, instead of a python variable.
如果它同时用于读写,我可能会使用我已经使用Django的数据库后端,而不是python变量。
If you could provide a more detailed description of what you're trying to achieve, perhaps we could come up with a better suited solution.
如果你能提供一个更详细的描述,你可能会想出一个更合适的解决方案。