Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A variable shared between views and initialized in AppConfig

Tags:

python

django

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 

I can't store my_var into the session because the session isn't available at WebConfig.

How can I do that then?

like image 316
Incerteza Avatar asked Mar 06 '15 21:03

Incerteza


1 Answers

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

Note the global keyword.

like image 149
catavaran Avatar answered Oct 01 '22 05:10

catavaran