Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - create a class instance in AppConfig.ready() only once

Tags:

I need to create a class instance (lets say backend requests session) on the app startup(runserver), and I don't want to rewrite this session after running other management command. How can I achieve this? I tried several approaches and I'm not sure why something like this doesn't work.

# app/apps.py
class MyConfig(AppConfig):
    ....
    requests_session = None
    ....
    def ready(self):
        if MyConfig.requests_session is None:
            MyConfig.requests_session = requests.Session()

Unfortunately, the condition is always met and the session is recreated. This approach is recommended in the documentation though.

Other solution for me would be to run MyConfig.ready() only after using selected subset of management commands, is that possible?

Is there completely different better way for me to store requests session?

TIA

like image 923
David Viktora Avatar asked Jul 26 '16 15:07

David Viktora


1 Answers

I think it should work if you use an instance variable instead of a class variable:

# app/apps.py
class MyConfig(AppConfig):

    def __init__(self, app_name, app_module):
        super(MyConfig, self).__init__(app_name, app_module)
        self.requests_session = None

    def ready(self):
        if self.requests_session is None:
            self.requests_session = requests.Session()

The question now is how to access this instance variable elsewhere. You can do that like so:

from django.apps import apps

# Here myapp is the label of your app - change it as required
# This returns the instance of your app config that was initialised
# at startup.
my_app_config = apps.get_app_config('myapp')

# Use the stored request session
req = my_app_config.requests_session

Note that this instance variable only exists in the context of the current process. If you run a management command in a separate process (e.g., manage.py ...) then that will create a new instance of each app.

like image 134
solarissmoke Avatar answered Sep 28 '22 02:09

solarissmoke