Working with static methods/variables

Asked

Viewed 70 times

2

Expensive,

When calling a python class, the variables of that class will always be restarted?

What happens is this: I’m working with the parallelization of my code. I receive the data returned from the database, break them into several Hunks and send Celery these Hunks, so that it processes and saves the results in a list. For this, I have a controller class that has two static methods. The first one must save the values it receives in a list. The second must take this list, order and return its first value. My class is the following:

class chunkControler:

    value = []

    @staticmethod
    def setregisterpercent(registerpercent):
        __class__.value.append(registerpercent)

    @staticmethod
    def getvalue():
    __class__.value.sort()
    return __class__.value[0]

To save the values, I call this class as follows in my task:

from .chunkControler import chunkControler
chunkControler.setregisterpercent(registerpercent)

and to recover the values, I do as follows in my view:

from .chunkControler import chunkControler
resultado = chunkControler.getvalue()
    print(resultado)

(The Imports are being made at the beginning of tasks.py and views.py)

The problem is that when I call the method chunkControler.getvalue(), the return is being from the empty list, as if a new list were created for this return. Is there any way to circumvent this and return the list that was initially created?

  • 1

    https://repl.it/repls/JampackedBriskCookies

  • Thanks for the reply, my program is with the same structure, but I continue to receive as return an empty list. I guess it must be some problem with Celery then.

  • Maybe you’re trying to get the data ahead of time (since Celery is based on asynchrony)

1 answer

1


Do not store values this way. The explanation is complex, but basically Django doesn’t work this way, you can’t write "global" variables or store anything in static classes, this is highly not recommended, especially using Celery.

My tip is, to save and rescue values use the bank, if this value is not so "precious" use cache. (I recommend the memory cache because it is very fast)

cache.set('my_key', 'hello, world!', 30)
cache.get('my_key')

Django cache

In Settings, use a backend of your choice, I put example the cache using local memory:

CACHES = {
'default': {
    'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
    'LOCATION': 'unique-snowflake',
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.