`
hqman
  • 浏览: 361575 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

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:

export 
DJANGO_SETTINGS_MODULE
=
yoursite.settings

Then you can just run any scripts which rely on Django settings, and they’ll work properly. If you’re using a different shell, or if you’re on Windows, the exact command to type will be slightly different, but the idea is the same.

One extremely useful application of this is in a crontab file; cron lets you set and change environment variables with ease, so you can have things like this in your crontab :

# Cron jobs for foo.com run at 3AM


DJANGO_SETTINGS_MODULE
=
foo.settings

0 3 * * * python /path/to/maintenance/script.py
30 3 * * * python /path/to/other/script.py

# Cron jobs for bar.com run at 4AM


DJANGO_SETTINGS_MODULE
=
bar.settings

0 4 * * * python /path/to/maintenance/script.py
30 4 * * * python /path/to/other/script.py

This is pretty much exactly what the crontab files on our servers at World Online look like, and in general this is the cleanest way to handle scripts which use Django components and need to run as cron jobs.

Use setup_environ()

Back in May, Jared Kuolt wrote up this technique , which is exactly how Django’s own manage.py script handles settings: the function setup_environ() in django.core.management will, given a Python module containing Django settings, handle all the business of (appropriately for its name) setting up your environment for you:

from
 django.core.management
 import
 setup_environ

from
 mysite
 import
 settings


setup_environ
(
settings
)

Below the setup_environ() line, you can make use of any Django component and rest assured that the proper settings will be available for it.

The only real disadvantage to this is that you lose some flexibility: by tying the script to a particular settings module, you’re also tying it to a particular Django project, and if you later want to re-use it you’ll have to make a copy and change the import to point at another project’s settings file, or find a different way to configurably accept the settings to use (we’ll look at that again in a moment). If all you need is a one-off script for a particular project, though, this is an awfully handy way to set it up.

Use settings.configure()

For cases where you don’t want or need the overhead of a full Django settings file, Django provides a standalone method for configuring only the settings you need, and without needing to use DJANGO_SETTINGS_MODULE : the configure() method of the LazySettings class in django.conf (django.conf.settings is always an instance of LazySettings , which is used to ensure that settings aren’t accessed until they’re actually needed). There’s official documentation for this , and it’s fairly easy to follow along and use it in your own scripts:

from
 django.conf
 import
 settings


settings
.
configure
(
TEMPLATE_DIRS
=
(
'/path/to/template_dir'
,),
 DEBUG
=
False
,

                   TEMPLATE_DEBUG
=
False
)

And then below the configure() line you’d be able to make use of Django’s template system as normal (because the appropriate settings for it have been provided). This technique is also handy because for any “missing” settings you didn’t configure it will fill in automatic default values (see Django’s settings documentation for coverage of the default values for each setting), or you can pass a settings module in the default_settings keyword argument to configure() to provide your own custom defaults .

Like setup_environ() , this method does tie you down to a particular combination of settings, but again this isn’t necessarily a problem: it’s fairly common to have project-specific scripts which won’t need to be re-used and rely on some values particular to that project.

Accept settings on the command line

We’ve seen that setup_environ() and settings.configure() both seem to tie you to a particular settings module or combination of manually-provided settings, and while that’s not always a bad thing it presents a major stumbling block to reusable applications. Setting DJANGO_SETTINGS_MODULE (as seen above in the context of a crontab ) is much more flexible, but can be somewhat tedious to do over and over again. So why don’t we come up with a method that lets you specify the settings to use when you call the script?

As it turns out, this is extremely easy to do; I think the technique doesn’t get a lot of attention because most newcomers to Django don’t yet know their way around Python’s standard library and so don’t stumble across the module which makes it all simple: optparse . In a nutshell, optparse provides an easy way to write scripts which take traditional Unix-style command line arguments, and to get those arguments translated into appropriate Python values.

A simple example would look like this:

import
 os

from
 optparse
 import
 OptionParser


usage
 =
 "usage: %prog -s SETTINGS | --settings=SETTINGS"

parser
 =
 OptionParser
(
usage
)

parser
.
add_option
(
'-s'
,
 '--settings'
,
 dest
=
'settings'
,
 metavar
=
'SETTINGS'
,

                  help
=
"The Django settings module to use"
)

(
options
,
 args
)
 =
 parser
.
parse_args
()

if
 not
 options
.
settings
:

    parser
.
error
(
"You must specify a settings module"
)


os
.
environ
[
'DJANGO_SETTINGS_MODULE'
]
 =
 options
.
settings

There’s a lot going on here in a very small amount of code, so let’s walk through it step-by-step:

  1. We import the standard os module and the OptionParser class from optparse .
  2. We set up a usage string; optparse will print this in help and error messages.
  3. We create an OptionParser with the usage string.
  4. We add an option to the OptionParser : the script will accept an argument, either as -s or as the long option settings , which will be stored in the value attribute “settings” of the parsed options, and we provide it with some explanatory text to show in help and error messages.
  5. We parse the arguments from the command line using parser.parse_args() .
  6. We check to see that the “settings” argument was supplied, and direct the parser to throw an error if it wasn’t.
  7. We use os.environ to set DJANGO_SETTINGS_MODULE .

Not bad for about ten lines of easy-to-write code; once that’s been done, DJANGO_SETTINGS_MODULE will have been set and we can use any Django components we like. Running the script will look like this:

python myscript.py --settings=
yoursite.settings

The parser created with optparse will handle the parsing; it’ll also automatically enable a “help” option for the -h or —help flags which will list all of the available options and their help text, and show appropriate error messages when the required “settings” argument isn’t supplied.

Because optparse makes it easy to pack a lot of configurability into a small amount of code, it’s generally my preferred method for writing standalone scripts which need to interact with Django, and I highly recommend spending some time with its official documentation . If you’d like to use one of the other configuration methods — setup_environ() or settings.configure() — it’s relatively easy to write an optparse -based script which does the right thing.

And that’s a wrap

Each of these methods is appropriate for different types of situations, and depending on exactly what you need to do you may end up using all of them at various times. Personally, I tend to either write scripts which use optparse and take a command-line argument for settings, or (for maintenance tasks which will run in cron ) to write scripts which just assume DJANGO_SETTINGS_MODULE is taken care of in advance, but all of these methods can be useful, so keep them all in mind whenever you find yourself needing a standalone script that uses Django.

分享到:
评论

相关推荐

    standalone_scripts:各种独立脚本

    "standalone_scripts"是一个集合,包含各种独立的脚本,它们可以单独运行,完成特定的任务。这些脚本通常由开发人员或系统管理员创建,以提高效率,解决特定问题,或者执行日常维护工作。在"standalone_scripts-...

    django-nameko-standalone:在您的nameko微服务中使用Django ORM

    DJANGO NAMEKO STANDALONE在您的nameko服务中使用django要求为Python3.6开发。 具有以下方面的依存关系: 的Django == 3.0.7 nameko == 2.12.0安装pip install django-nameko-standalone 用法该软件包设置了django...

    All-StandAlone-Django-Projects

    【标题】"All-StandAlone-Django-Projects" 是一个集合了多个独立Django项目的资源包,旨在帮助开发者学习和实践使用Django框架构建独立的Web应用。Django是Python编程语言中的一款强大且流行的Web开发框架,以其...

    VMware Converter Standalone 6.1.1

    VMware Converter Standalone 6.1.1 是一款强大的工具,专为将物理服务器、物理台式机或第三方虚拟机转换为VMware虚拟机而设计。这个版本是针对Windows操作系统的独立安装程序,旨在帮助用户无缝迁移他们的IT基础...

    standalone:独立版可让您从Python模块访问Django Shell

    单机版使用Standalone,您可以从Python模块访问Django Shell,也可以将django模块作为可访问Django Shell的独立模块运行。安装pip install standalone配置1.使用当前项目的Django shell。 用于在同一Django项目中的...

    VMware vCenter Converter standalone 6.2 guide

    VMware vCenter Converter Standalone 是一款能够将物理服务器和虚拟机转换为VMware虚拟机格式的工具。VMware vCenter Converter Standalone 6.2为最新版本,通过这款工具可以进行数据克隆和系统配置,支持对运行中...

    jython-standalone-2.7.0.zip

    标题 "jython-standalone-2.7.0.zip" 提供了我们正在处理的是一个Jython的独立版本,具体是2.7.0的发行版。Jython是一种Python的实现,它允许Python代码在Java平台上运行。这个压缩包很可能包含了一个完整的Jython...

    TSC Standalone Creator中文使用说明书.pdf

    TSC Standalone Creator 是一款由TSC Auto ID Technology Co., Ltd开发的专业条形码打印机软件,主要用于创建和编辑打印任务,尤其适用于需要自定义触控面板界面的用户。该软件提供了丰富的功能,让用户能够轻松设计...

    jython-standalone-2.7.2.jar

    jython-standalone-2.7.2.jar,java应用调用Python。

    含两个文件hive-jdbc-3.1.2-standalone.jar和apache-hive-3.1.2-bin.tar.gz

    含两个文件hive-jdbc-3.1.2-standalone.jar和apache-hive-3.1.2-bin.tar.gz 含两个文件hive-jdbc-3.1.2-standalone.jar和apache-hive-3.1.2-bin.tar.gz 含两个文件hive-jdbc-3.1.2-standalone.jar和apache-hive-...

    tyrus-standalone-client-1.13.1.jar

    tyrus-standalone-client-1.13.1.jar

    django-models-standalone

    django-models-standalone 这只是django框架之上的包装程序包,它仅包含独立模块来创建django项目。如何1.安装django-models-standalone: python setup.py install 2.创建独立的Django模型项目: cd ~django-models...

    jython-standalone-2.7.0(最新版本)

    一个将Python代码转换成Java代码的编译器,能够将自己用Python代码写的类库用...Jython环境安装包: http://search.maven.org/remotecontent?filepath=org/python/jython-standalone/2.7.0/jython-standalone-2.7.0.jar

    selenium-server-standalone-3.141.59.jar

    《Selenium Server Standalone 3.141.59:自动化测试的得力助手》 Selenium Server Standalone 3.141.59.jar 是一款强大的自动化测试工具,它在软件测试领域占据着重要的地位,尤其在Web应用程序的自动化测试中不可...

    JIRA 4.2 Standalone安装指南

    ### JIRA 4.2 Standalone安装指南知识点详解 #### JIRA 4.2 Standalone安装概述 JIRA是一款强大的项目管理和缺陷跟踪工具,适用于软件开发团队和其他需要管理任务和项目进度的团队。本指南主要介绍了JIRA 4.2 ...

    selenium-server-standalone-3.6.0.jar

    《Selenium Server Standalone 3.6.0:网页自动化测试的强大工具》 Selenium Server Standalone 3.6.0.jar 是一个重要的自动化测试工具,尤其在IT行业的Web应用测试领域,它扮演着不可或缺的角色。这个Java包是...

    hive-jdbc-3.1.2-standalone

    hive-jdbc-3.1.2-standalone适用于linux

    selenium-server-standalone-2.40

    在这个名为 "selenium-server-standalone-2.40" 的压缩包中,包含了Selenium Server的独立版本以及相关的Java库。 1. **Selenium Server Standalone**: Selenium Server Standalone是Selenium的核心组件之一,它...

    jackrabbit-standalone

    jackrabbit-standalone-1.6.5.jar是webDav的支持jar包。

    mule-standalone-3.9.0.zip

    "mule-standalone-3.9.0.zip"是一个包含Mule ESB独立运行时环境的压缩包,版本为3.9.0。在本文中,我们将深入探讨Mule ESB的核心概念、功能以及3.9.0版本的特性。 Mule ESB是基于Java的轻量级服务导向架构(SOA)...

Global site tag (gtag.js) - Google Analytics