Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Run a script right after runserver

Context:

I have a table on the database that uses values from an external database. This external database updates its values periodically.

Problem:

In order to update my database everytime i start the server, I want to run a script right after the runserver.

Potential Solution:

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

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!

Thanks in advance

Update

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.

like image 201
Alvaro Avatar asked Jan 17 '19 05:01

Alvaro


2 Answers

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()
like image 141
Exprator Avatar answered Sep 30 '22 06:09

Exprator


I would recommend to use something like this, lets say you have the script like this:

# abc.py

from your_app.models import do_something

do_something()

Now you can run this script right after runserver(or any other way you are running the django application) like this:

python manage.py runserver & python manage.py shell < abc.py

FYI, it will only work if you have bash in your terminal (like in ie Linux, MacOs).

Update

After reading you problem carefully, I think running a script after runserver might not be the best solution. As you said:

This external database updates its values periodically.

So, I think you need some sort of perodic task to do this update. You can use cronjob or you can use Celery for this.

like image 20
ruddra Avatar answered Sep 30 '22 04:09

ruddra