Django使用管理和共享d

2024-09-29 17:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是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”对象。到目前为止,我正在将读取的属性存储在数据库中,以便每个应用程序都可以从那里获取它

有什么意见或想法吗?你知道吗


Tags: the对象fromimportself应用程序basereturn

热门问题