Django:在runserver之后立即运行脚本 [英] Django: Run a script right after runserver
问题描述
上下文:
我在数据库上有一个表,该表使用来自外部数据库的值.该外部数据库会定期更新其值.
I have a table on the database that uses values from an external database. This external database updates its values periodically.
问题:
为了在每次启动服务器时更新数据库,我想在runserver之后立即运行脚本.
In order to update my database everytime i start the server, I want to run a script right after the runserver.
潜在的解决方案:
我已经看到可以从某个应用程序运行脚本,这是我感兴趣的事情.这可以通过使用 django-extensions
来实现:
I have seen that it is possible to run a script from a certain app, which is something I'm interested in. This is achievable by using the django-extensions
:
https://django-extensions.readthedocs.io/en/latest/runscript.html
但是,此脚本仅使用以下命令运行:
However, this script only runs with the following command:
python manage.py runscript your_script
还有其他方法可以从应用程序运行脚本并在runserver命令之后立即执行该脚本吗?我愿意接受建议!
Is there any other way to run a script from an app and execute it right after the runserver command? I am open to suggestions!
预先感谢
更新
感谢@Raydel Miranda的发言,我觉得我留下了一些信息.
Thanks to @Raydel Miranda for the remarks, I feel i left some information behind.
我的目标是,一旦启动服务器,我打算打开一个套接字来维护数据库的更新.
My goal is, once I start the server I'm planning to open a socket to maintain my database updated.
推荐答案
您可以在顶级 urls.py
中执行代码.该模块将被导入并执行一次.
You can execute the code in the top-level urls.py
. That module is imported and executed once.
urls.py
from django.confs.urls.defaults import *
from your_script import one_time_startup_function
urlpatterns = ...
one_time_startup_function()
这篇关于Django:在runserver之后立即运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!