Django does not provide any way, per se, of doing that. Using global variables is, most of the times, a bad idea. My suggestion comes in the following steps:
- If you are forced to store such values in memory, use a Singleton object instead of a plain global variable (on the end, you are assuming the same risks, or similar, so be wary).
- Declare methods to access the object and make the data available or store new values.
- Remember this approach may fail (actually not fail but become less efficient) in development since stuff can be reloaded.
- Remember to make those methods thread safe: my suggestion is you use a mutex.
Remember that, in Python, either you store something in a member of a global reference, or declare a global variable. This is a minor adjustment of what you did:
def startLoading():
global p, songs
# If you don't acquire a mutex here, God will flood earth again
if not (p or songs):
p, songs = loadSongs()
# release the mutex
return p, songs
I always suggest having another reference to store everything (the singleton I told you later):
from a.certain.module import my_store
def startLoading():
# ACQUIRE MUTEX here
if not myStore.has_data():
my_store.set_data(loadSongs())
# RELEASE MUTEX here
return my_store.get_data()
What get_data
, set_data
, and has_data
do is up to you. I still think storing global values is a terrible idea in particular if you use something like gunicorn and have several (2n+1) django processes attending clients. It is always preferrable an external process like memcache to achieve that. But if you insist, you have these guidelines.