Search code examples
pythondjangodjango-settings

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.


Solution

  • 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()