我正在使用Django 1.9.3。我有一个项目与几个应用程序。我想在项目启动时更新其中一个应用程序的表格。Django - 在启动时执行代码
用例:
例如,假设我想卖掉我的网站上的项目。我有一个包含模型Item的应用程序。我在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 ;-)
我的问题是我不知道在哪里可以编写代码
尝试:
到目前为止,在Django 1.6.5中,我使用了我的应用的init .py文件中的一些代码。它正在工作,但我认为它非常难看(用“导入”开始线程看起来非常像隐藏的代码)。
我在Django 1.9中看到了“ready()”方法。但它写在文档中,不处理这种方法中的模型,所以我很困惑。
我可以在启动我的服务器的命令中添加启动代码,但此启动代码是面向应用程序的,在我看来,这些项目与它无关。
你会推荐什么?
如果需要,我很乐意提供更多信息。
由于提前,
你可能会发现一些有用的[这个stackoverflow问题](http://stackoverflow.com/questions/2781383/where-to-put-django-startup-code)。 – Robin
我已经看到它了,这个链接的接受答案提到了像我这样的“ready()”方法。但根据Django doc,在这种方法中与模型进行交互是一种不好的做法...... –
“启动”在这种情况下意味着什么?通常你会开始一个网站,然后继续运行。为什么您需要在“启动”时填充表格,而不是在迁移中? –