E
E
Evgeny_A2021-04-16 18:14:59
Django
Evgeny_A, 2021-04-16 18:14:59

How to use the same variable instance in different Django applications?

Hello.

I have a large variable that I load once to speed up the processing of user requests. Here is the project/app1/apps.py file

from django.apps import AppConfig

class Config(AppConfig):
    data = load_data()

Further, in any model, it is very easy to access this data:

from django.apps import apps

settings = apps.get_app_config('app1')
# Здесь данные, которые я присвоил переменной в apps.py
data = settings.data

The problems started when I needed to access data from another application. When I access settings.data from another application, the big data is loaded from scratch and two instances of the same variable hang in memory. This takes up a lot of space and updates to one instance are not available in another.

The question is how to load data in one application so that it and other applications use the same instance of the variable? I need to store a common set of data in memory so that changes are instantly available to all applications.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JRazor, 2021-04-16
@JRazor

According to the description - the problem should be solved completely differently than described in the question.

  1. Putting data in a file
  2. Create a singleton class above the application
  3. Upload the file there
  4. Import the class when and where needed

Why shove it into the app is not clear. As if he is directly obliged to see that you have Django, feel it, touch it, and then start. Read SoC

D
Dmitry, 2021-04-17
@pyHammer

Evgeny_A django already has a similar mechanism in the sites app. You should do something like this:

# file_1.py
BIG_VAR = []

class BigVarClass:
    @staticmethod
    def get_big_var(self):
        return BIG_VAR
    @staticmethod
    def set_big_var(self, big_var):
        global BIG_VAR
        BIG_VAR = big_var

# file_2.py
from .file_1 import BigVarClass

BIG_VAR = BigVarClass.get_big_var()

A rough example, but it works somehow like this
Well, actually the link to github django/contrib/sites/models.py

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question