tags:

views:

108

answers:

3

Hi,

How can I create an application scope variable which is loaded when the django app starts, be in memory and accessible by all.

Basically I want to reuse the variable through out the application without reloading it.

Thanks

A: 

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.

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.

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.

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.

lemonad
I guess the problem is that a variable in settings.py is in project-scope. To have a variable for app a settings file inside the app or possibly definition in __init__.py of the app might work.
kioopi
got the underscores removed from around init
kioopi
Actually I want to load a heavy array from the database (skipping direct db call)
Vishal
For your next question, I recommend including that kind of information in order to help the people answering.I would likely have used memcache in your situation.
lemonad
+3  A: 

You could add it to your settings.py file. Or, add it to the __init__.py file inside the app directory.

scompt.com
A: 

Are you referring to something like an environment variable? You could load it via init...

__init__.py

import os
os.environ['APP_VAR_WHATEVER'] = 'hello world!'
T. Stone