视图之间共享并在AppConfig中初始化的变量 [英] A variable shared between views and initialized in AppConfig
本文介绍了视图之间共享并在AppConfig中初始化的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个变量,该变量在应用程序启动时初始化,并且可以从视图中访问该变量:
I want to have a variable which I initialize as the application startup and to which I get get access from the views:
# my_app/my_config.py
class WebConfig(AppConfig):
name = '....'
verbose_name = '....'
def ready(self):
print('loading...')
warnings.filterwarnings("ignore")
my_var = {}
# my_app/views.py
def index(request):
# my_var isn't accessible
我无法将 my_var
存储到会话中,因为该会话在WebConfig中不可用.
I can't store my_var
into the session because the session isn't available at WebConfig.
那我该怎么办?
推荐答案
在 my_config
中的模块级别定义 my_var
,然后将其导入观看次数
:
Define the my_var
at the module level in the my_config
and then import it in the views
:
my_app/my_config.py
my_var = None
class WebConfig(AppConfig):
...
def ready(self):
global my_var
my_var = {}
my_app/views.py
from my_app.my_config import my_var
def index(request):
print my_var
请注意 global
关键字.
Note the global
keyword.
这篇关于视图之间共享并在AppConfig中初始化的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文