我正在使用 Django (1.9),我想在管理命令之间共享类对象。
假设 - 简单地说 - 我有一个主应用程序,它实例化了一些类。
my_main_app/commands/mananagement/setup.py
#!/usr/bin/env python
from django.core.management import base, call_command
from somewhere import SingletonClass
class Command(base.BaseCommand):
'''
Overloads runserver command by creating a few extra objects
'''
def handle(self, *args, **options):
myObject = SingletonClass(date = datetime.now())
call_command("runserver") # this doesn't return
我想要的是在另一个命令行调用中访问“myObject”对象。例如,我想知道 myObject 对象何时被实例化。
my_other_app/commands/mananagement/command.py
#!/usr/bin/env python
from django.core.management import base, call_command
from somewhere import SingletonClass
class Command(base.BaseCommand):
def handle(self, *args, **options):
myObject = SingletonClass() # <- this should be the same instance than the object created in the main app
return myObject.date # must return the date of the call to the setup command
在示例中,我使用单例模式,因为它似乎接近我想要的。
到目前为止,我只找到了以下解决方案:
1)主应用程序创建一个监听命令行调用的服务器
from somewhere import SingletonClass, Server
class Command(base.BaseCommand):
def handle(self, *args, **options):
self.myObject = SingletonClass(date = datetime.now())
self.__server = Server(handler = self.handle_distant)
self.__server.start() # this starts a listening server
def handle_distant(self, *args, **kwargs):
'''
this method is called from distant
client calls
'''
return call_command(*args, **kwargs)
2)另一个应用程序是该服务器的客户端:
from somewhere import SingletonClass, Client
class Command(base.BaseCommand):
def handle(self, *args, **options):
if options["local"] = True: # wil be True when called from the main app
return SingletonClass().date
else:
client = Client()
options["local"] = True
return client.doSomething(*args, **options)
这可以工作,但我有一个手动序列化(在客户端)和反序列化(在服务器端)每个命令。我觉得它很难看,我想知道是否有使用 Django 的最佳方法。
我还可以使用数据库来存储我想要共享的每个对象,但它似乎并不好。
下面的真实用例:
例如,我有一个名为“配置”的应用程序,它能够在文件系统上加载属性文件。(注意:我调用这里介绍的属性文件:docs.python.org/2/library/configparser.html)。当用户运行命令“load-config”时,此应用程序会加载属性文件。然后,我希望我的所有应用程序都可以访问之前加载的配置,而无需重新读取每个属性文件。我想为我的所有应用程序实例化一个“PropertyManager”对象。到目前为止,我将读取的属性存储在数据库中,以便每个应用程序都可以从那里获取它
有什么意见或想法吗?