Running a standalone django python script

They are 2 ways you can run Django as a standalone script. The first approach leverages on WSGI while the second approach uses Django admin commands by registering your own custom actions within manage.py. Why might you want to do this? In some instances they might be a need to run a script that performs some action, this could be an ad-hoc task such as data importing, data patching running custom logic that’s not user driven, perhaps even executing a cron job that fires your script on a periodical basis while still leveraging on your existing Django & ORM code base.

In this quick tutorial, we will be taking a look at the first approach which is relatively simple. If you understand how Django works then the answer pretty much lies inside your WSGI.py file that’s auto-generated for you if you’re using the django-admin startproject command to scaffold your initial Django project. You need to understand that all the bootstrapping and loading up of Django occurs directly within your wsgi.py and setting.py so we can create a script that calls the correct settings to run a Django script as a standalone program.

Let’s create a script called myscript.py which will be located into its own python module, that then loads up Django via WSGI. See code script below

location : djangoproject/scripts/myscript.py

Our little script doesn’t do much, it just checks if admin users exist in your database if a user is not found creates a new record or updates. Now all we need to do to execute the script is invoke it via our command prompt or Unix shell.

If we wished to take this a step further and run it periodically we could invoke this script via crontab or use supervisord to execute it as a service.

If you would like to learn more about Django and empower yourself with code checkout building your first Django app course in minutes, which covers lots of concepts to help you build your apps faster.

By | 2017-04-26T12:58:08+00:00 March 21st, 2017|Django|