30854

A variable shared between views and initialized in AppConfig

<h3>Question</h3>

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?


<h3>Answer1:</h3>

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.

来源:https://stackoverflow.com/questions/28907933/a-variable-shared-between-views-and-initialized-in-appconfig

Recommend

  • How To Do Model Predict Using Distributed Dask With a Pre-Trained Keras Model?
  • Adding long press gesture recognizer in Xamarin forms
  • Replace value with the average of it's column - many columns
  • Laravel error with 404 page
  • Issue while running Linux Command using Java?
  • Pretty URL & SEO-friendly URL?
  • Perl is respecting '
  • How to remove light's deflections [closed]
  • ruby: how to iterate elements in a hash efficiently
  • How to pivot table for year in SQL?
  • Add a new custom default ordering catalog option in Woocommerce
  • Preventing Internet-accessing-method from delaying a toast popup
  • Sending a PDF created dynamically as an attachment using PDFKit in a nodejs application
  • Jasmine unit testing observable subscribe does not trigger
  • How to split a string into a list by digits? [duplicate]
  • Repeatable job for Laravel json api
  • Trying to get lotusscript json reader
  • ASP.NET MVC 3 ListBox validation
  • Dynamic reference casting depending on actual object type
  • Bulk loading into PostgreSQL from a remote client
  • Webdriver 3.14 IE11: session lost when click link/button that opens a window/popup
  • Override all shipping costs for a specific shipping class in Woocommerce
  • integrity constraint violation: NOT NULL check constraint
  • Laravel 5 - Cache remember doesn't work
  • SELECT on JSONField with Django
  • yii rewrite url with many sub categories
  • Draw 9 patch dotted /dashed line on Android
  • Checking for valid enum types from protobufs
  • Add checkbox dynamically using angular 2
  • xpath assertion failure with dynamic xpath
  • how to run a different select statement based on condition in Hive SQL
  • Firebase: How to read from external DB?
  • convert json to excel in java
  • How to handle a codeigniter PDF generator