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.
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)
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.
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]