Django - 在启动时执行代码

Jul*_*ard 8 python django

我正在使用Django 1.9.3.我有一个包含多个应用程序的项目.我想在项目启动时更新其中一个应用程序的表.

用例:

例如,假设我想在我的网站上销售商品.我有一个包含模型项的应用程序.我在Django外面有一个Web服务,提供服务"give_all_items_available()".我想向我的用户提供使用该网站的项目列表.因此,我认为我必须定期(在启动时和每隔一段时间)使用该Web服务输入更新我的数据库.

我编写了所有代码,它看起来如下(这是一个例子):

from my_app.models import My_table

def on_startup():
     my_thread = Thread(execute = populate_tables, loopmode = True, background = True) # thread running in loopmode in background
     my_thread.start() # starts the thread and returns

def populate_tables()
     response = call_webservice() # let's imagine this method returns data for creating a new model instance
     My_table(response).save() # this save() isn't threadsafe in this example, but that's not my point ;-)
Run Code Online (Sandbox Code Playgroud)

我的问题是我不知道在哪里写这段代码

尝试:

到目前为止,使用Django 1.6.5,我从我的应用程序的init .py文件中获得了一些代码.它工作正常,但我觉得它很难看(开始一个带有"导入"的线程看起来非常像隐藏代码).

我在Django 1.9中看到了"ready()"方法.但它在文档中写的不处理这种方法中的模型,所以我很困惑.

我可以在启动我的服务器的命令中添加启动代码,但是这个启动代码是面向应用程序的,在我看来,这些项目与它无关.

你会推荐什么?

如果需要,我很乐意提供更多信息.

提前致谢,

tri*_*het 1

为什么你不用芹菜代替呢?我知道您在问如何在启动时填充您的 Item 表,但是...我认为这里的计划芹菜任务适合并以自然的方式解决您的问题。