Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an object into memory for entire django project to see?

Tags:

python

django

I'd assume it would just be loaded into settings.py, and then the object would just be imported from the settings, but I just wanted to know if there was a more standard or recommended way to do this. Where do people usually load their items that their entire project needs see?

Ex.

# settings.py
...
something_large = json.loads(...)


# whatever models.py, views.py, etc
from Project.settings import something_large  #Is this the proper way to do it?

Thanks.

like image 579
Lucas Ou-Yang Avatar asked Jul 23 '13 22:07

Lucas Ou-Yang


1 Answers

You could load it in, say, a data module in your app to make it cleaner.

(I'm also showing how to load a file from the same directory a module is in.)

project/
   settings.py
   ...
myapp/
   __init__.py
   data.py
   huge_static_data.json
   models.py
   ...

myapp/data.py:

with file(os.path.join(os.dirname(__file__), "huge_static_data.json")) as in_f:
  something_large = json.load(in_f)

myapp/models.py:

from myapp.data import something_large

Python's import system ensures the data will just be loaded once, when the module is first imported.

like image 57
AKX Avatar answered Oct 13 '22 01:10

AKX