hqman 发表于 2013-1-15 02:18:56

Standalone Django scripts

In the grand tradition of providing answers to frequently-asked questions from the django-users mailing list and the #django IRC channel, I’d like to tackle something that’s fast becoming the most frequently-asked question: how do you write standalone scripts which make use of Django components?
At first glance, this isn’t a terribly hard thing to do: Django’s just plain Python, and all of its components can — in theory — be imported and used just like any other Python modules. But the thing that trips most people up is the need, in most parts of Django, to supply some settings Django can use so it’ll know things like which database to connect to, which applications are available, where it can find templates, etc.
Depending on exactly what you need to do, there are several ways you can approach this problem, so let’s run through each of them in turn.
Set DJANGO_SETTINGS_MODULE before you run

The simplest method is to simply assign a value to the DJANGO_SETTINGS_MODULE environment variable before you run your script, and that’s not terribly hard to do if you understand a little bit about how environment variables work. On most Unix-based systems (including Linux and Mac OS X), you can typically do this with the export command of the standard shell:
<div class="typygmentdown">export DJANGO_SETTINGS_MODULE=yoursite.settings
页: [1]
查看完整版本: Standalone Django scripts