In a django project, you need to implement access in the methods of the models to the information calculated by request. Information needs to be calculated once (several parameters), and somehow stored and transmitted. How to do it right? (With the help of Signleton, if I understand correctly, it will turn out to be a non-thread-safe solution).

  • Would not it be more logical to store this information in the database? Add specifics, what is this information? - awesoon
  • Singleton can be made thread-safe, but you still don’t have to do such a mess. - andreymal
  • one
    It really needs something like a global variable. The project (online store) implements a website with a system of regional subdomains (spb.site.ru, kazan.site.ru, etc. - there may be many subdomains, therefore, SITE_ID in settings will not work). There are various parameters set in the admin panel - for example, a correction factor to prices (linked to a subdomain). It seems much clearer to make middleware for calculating the necessary parameters (depending on the request) and to do @property price () in the models (by setting base_price), than to rewrite half of logic (order placement / basket / templates). - artbataev

2 answers 2

Why don't you use the environment variable:

import os os.environ['GLOBAL_VARIABLES'] = {'var1': 1, 'var2': 2} 

By the way, to launch a django project via wsgi, this trick is used (to somehow refer to the project settings for all running python instances).

    How much I have not tried to find information about global variables in django, they say everywhere that it is not advisable to use them. If you want to use them, then it is invoked as in python. Why don't you try this solution to your problem ?

    • Did not quite understand: why link to urlconf? - artbataev
    • In fact, there is a SITE_ID in Django, which is set in the settings. But mine is determined dynamically, and a lot depends on it. Passing a request to all the methods of a model is much worse than a global variable, in my opinion. - artbataev