我正在使用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,在這種方法中與模型進行交互是一種不好的做法...... –
「啓動」在這種情況下意味着什麼?通常你會開始一個網站,然後繼續運行。爲什麼您需要在「啓動」時填充表格,而不是在遷移中? –