post

Running external scripts against Django Models

Django, the Python based web application framework, is an excellent Model/View/Controller application framework for rich website design.

A Django application runs under a web server. However, often it is necessary to develop external scripts that need to interact with you web application data models. This brief tutorial will walk through an example. This may not necessarily be the _best_ way to do this, but merely a way. I struggled for a few hours on this last night and thought it would be useful to others to document my results.

Let’s look at an example. Feel free to take this and modify it as needed. It’s a bit contrived but will suit our purposes.

Suppose you have written a blog application and you want to periodically purge old entries. In your Model, you have written code to to all of the heavy lifting. Now, you want to make sure that these updates happen at a scheduled interval.

Assume your project lives in c:\project\blogprj

import sys,os
from datetime import *
sys.path.append('c:\\project')
os.environ['DJANGO_SETTINGS_MODULE'] ='blogprj.settings'

from django.core.management import setup_environ
from blogprj import settings

from blogprj.blog.models import Entry

setup_environ(settings)

blogs = BlogEntry.objects.all()

for entry in blogs:
     entry.purge_oldentries(date.today())

Let’s take a closer look at this.

sys.path.append('c:\\project')

This line appends your project directory to the python module search search path so that it can find the your packages. Remember, when django creates your template, it creates an __init__.py file in each directory of your project and apps. These __init__.py files tell python to treat the entire directory as a python package. If you set your module path to c:\\project\\blog then python will not be able to find the root of your packages (blog)

os.environ['DJANGO_SETTINGS_MODULE'] ='blogprj.settings'
The DJANGO_SETTINGS_MODULE variable tells your django application the name of the settings module. It uses the Python path syntax.

from django.core.management import setup_environ
from blogprj import settings

Since you are using Django libraries, you must tell it where to find your settings.py file. This is done through the function setup_environ and your project settings, imported here.

from blogprj.blog.models import Entry

We are going to be working with the Entry model, so we need to import it.

setup_environ(settings)

As stated previously, we must tell Django to use our project settings. This is necessary so Django can know what database we use, our installed apps, etc. This is handled by the setup_environ() method which takes a Settings object as a parameter.

Once this is done, the rest of the application merely performs the work against the model.

Save this script and you can run it inside your favorite scheduler, on Windows, we use Task Scheduler.

I hope this small tutorial has given you a little insight in how to call Django from external scripts. I welcome your comments.
[tags]Django, Development, Python, tutorial[/tags]

Comments

  1. a couple of things
    Firstly
    from blogprj.import settings
    doesn’t look right .. so using

    in windows how do you set the the environment variables, the script is trying to import the setting from a previous project?

  2. Ooofa, thanks for catching that. I’ve updated the tutorial and added a call to set the environment variables directly inside the Python script.

  3. from blogprj.import settings

    should be

    from blogprj import settings

  4. AK – thanks, didn’t catch the other import.

  5. jeffkwiat says:

    Thanks for the article!…exactly what I needed. BTW, nice last.fm playlist :).

  6. Excellent! This saved me a huge amount of time with writing a udp app that updates a db used by one of my django projects.

  7. Thanks a lot. This is what exactly am looking for. I tried the same way but I missed setting up of paths properly.

  8. Matthias says:

    Thanks a lot.
    Little remark: I have to run the setup_environ(settings) before I can import Models.
    Works well in the sequence:
    1. setup_environ(settings)
    2. from blogprj.blog.models import Entry

  9. Thanks for this blog. I am new at development and this will be a big help.

  10. Thanks a lot. This is what exactly am looking for. I tried the same way but I missed setting up of paths properly.

  11. thanks

  12. Thanks Joe for thanking your time to share with us your results. I have one question regarding to your study; How do I use an external script inside of Django properly?

    Looking all over the web to find something as a good start for my scenario but didn’t find by now; hope that I’ll find soon :)

    I’m getting an error that the module (Python module) is not imported correctly;

  13. Kevin Alone says:

    neat, thank you!
    I had to change it a bit:
    from blogproj import settings
    setup_environ(settings)
    from blog.models import Entry
    works awesome!

Leave a Reply