Python 如何将对象加载到内存中,以便整个django项目都能看到?
我假设它将被加载到settings.py中,然后从settings中导入对象,但我只是想知道是否有更标准或更推荐的方法来实现这一点。人们通常在哪里加载整个项目需要查看的项目 前Python 如何将对象加载到内存中,以便整个django项目都能看到?,python,django,Python,Django,我假设它将被加载到settings.py中,然后从settings中导入对象,但我只是想知道是否有更标准或更推荐的方法来实现这一点。人们通常在哪里加载整个项目需要查看的项目 前 谢谢。您可以将其加载到应用程序的数据模块中,使其更干净 (我还展示了如何从模块所在的同一目录加载文件。) myapp/data.py: with file(os.path.join(os.dirname(__file__), "huge_static_data.json")) as in_f: something_l
谢谢。您可以将其加载到应用程序的
数据模块中,使其更干净
(我还展示了如何从模块所在的同一目录加载文件。)
myapp/data.py
:
with file(os.path.join(os.dirname(__file__), "huge_static_data.json")) as in_f:
something_large = json.load(in_f)
from myapp.data import something_large
myapp/models.py
:
with file(os.path.join(os.dirname(__file__), "huge_static_data.json")) as in_f:
something_large = json.load(in_f)
from myapp.data import something_large
Python的导入系统确保在第一次导入模块时只加载一次数据 我喜欢这个答案,但前提是数据属于应用程序。或者,我认为将其加载到主项目中会更有意义。当然。如果项目中的多个应用程序需要相同的数据,最好使用一个“通用应用程序”将其放入项目目录,而不是“污染”项目目录。