本文介绍了Django-仅在AppConfig.ready()中创建一个类实例一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在应用程序启动(运行服​​务器)上创建一个类实例(让我们说后端请求会话),并且我不想在运行其他管理命令后重写此会话.我怎样才能做到这一点?我尝试了几种方法,但不确定为什么这样的方法行不通.

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.

对我来说,其他解决方案是仅在使用选定的管理命令子集之后运行MyConfig.ready(),这可能吗?

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

推荐答案

认为如果您使用实例变量而不是类变量,它应该可以工作:

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

请注意,此实例变量仅存在于当前进程的上下文中.如果您在单独的进程(例如 manage.py ... )中运行管理命令,则将为每个应用程序创建一个新实例.

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.

这篇关于Django-仅在AppConfig.ready()中创建一个类实例一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 15:10