我需要在应用程序启动(runserver)上创建一个类实例(假设后端请求会话),并且我不想在运行其他管理命令后重写此会话。我怎样才能实现这个目标?我尝试了几种方法,但我不确定为什么这样的方法不起作用。
# app/apps.py
class MyConfig(AppConfig):
....
requests_session = None
....
def ready(self):
if MyConfig.requests_session is None:
MyConfig.requests_session = requests.Session()
Run Code Online (Sandbox Code Playgroud)
不幸的是,总是满足条件并重新创建会话。不过,文档中推荐使用这种方法。
对我来说,其他解决方案是仅在使用选定的管理命令子集后运行 MyConfig.ready(),这可能吗?
有没有完全不同的更好的方法来存储请求会话?
TIA
我认为如果您使用实例变量而不是类变量,它应该可以工作:
# 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()
Run Code Online (Sandbox Code Playgroud)
现在的问题是如何在其他地方访问这个实例变量。你可以这样做:
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
Run Code Online (Sandbox Code Playgroud)
请注意,该实例变量仅存在于当前进程的上下文中。如果您在单独的进程中运行管理命令(例如,manage.py ...),那么这将为每个应用程序创建一个新实例。