- 浏览: 352624 次
- 性别:
- 来自: 苏州
文章分类
最新评论
-
hqman:
export LD_PRELOAD=/lib/libpam.s ...
OpenVPN 详细配置 -
wutao8818:
呵呵,标题挺好,内容没看
说话前你是话的主人,说话后你是话的仆人 -
wutao8818:
额,你需要的就是认准一件事。但说起来简单,对某些人来说这很难, ...
我很浮躁 -
damoqiongqiu:
可惜图片一个都没有了。
amf是什么东东 -
fzfx88:
貌似Apache + tomcate 可以解决
解决dwr跨域问题
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:
-
We import the standard
os
module and theOptionParser
class fromoptparse
. -
We set up a usage string;
optparse
will print this in help and error messages. -
We create an
OptionParser
with the usage string. -
We add an option to the
OptionParser
: the script will accept an argument, either as-s
or as the long optionsettings
, 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. -
We parse the arguments from the command line using
parser.parse_args()
. - We check to see that the “settings” argument was supplied, and direct the parser to throw an error if it wasn’t.
-
We use
os.environ
to setDJANGO_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.
发表评论
-
Gunicorn上跑pyramid
2011-12-08 20:48 1405看到 Instagram他们用了这个服务器于是仔细 ... -
pythonic用法
2011-11-04 14:36 780python 语言 倡导 简单 简洁 优美 记录一些 ... -
用pyexe把django应用打包成 windows上EXE可执行文件
2011-10-29 16:22 7897续上文 把django应用 打包 发布成 可 ... -
把django应用 打包 发布成 可独立运行的桌面程序
2011-10-26 23:20 6145把django应用 打包 发布成 可独立运行的桌面程序 ... -
Dropbox python开发中6点教训(每十五分钟同步100万个文件)
2011-10-08 12:51 2318Dropbox saves one million f ... -
python list 排序
2010-10-06 21:16 3146对于简单的list排序,直接调用内建函数就可以了,但是对于 ... -
python连mysql 数据库问题『 mysql 'latin-1' codec can't encode ch』
2010-09-25 17:11 1988class MysqlPipeline(objec ... -
python项目包管理
2010-09-19 14:17 1534最近学习django 进行web开发,在deploy程序是碰到 ... -
python 领域中的模板引擎 转
2010-06-10 20:14 3648GenShi 特点:解释型模板,纯粹面向 ... -
ssh 自动登录服务器脚本
2009-06-24 10:05 1238每次登录服务器 打很多字 好累,同事推荐了一个好东西。 ... -
Python-字符串操作方法
2009-01-14 14:05 1350Python-String-Function 字符串中字符 ... -
django通过gettext实现国际化
2008-10-21 16:00 1866Python 通过 gettext 模块支持国际化 (i1 ... -
lighttpd整合django(折腾了好几天终于搞定了)
2008-10-15 12:31 1699折腾了好几天终于搞定了 lighttpd的设置如下 ... -
ubuntu 7.10 Quixote 安装笔记
2008-10-04 16:41 1112wget http://quixote.ca/releas ...
相关推荐
DJANGO NAMEKO STANDALONE在您的nameko服务中使用django要求为Python3.6开发。 具有以下方面的依存关系: 的Django == 3.0.7 nameko == 2.12.0安装pip install django-nameko-standalone 用法该软件包设置了django...
standalone_scripts 各种独立脚本 每个脚本都有很好的注释; 阅读以了解目的和功能
All-StandAlone-Django-Projects
单机版使用Standalone,您可以从Python模块访问Django Shell,也可以将django模块作为可访问Django Shell的独立模块运行。安装pip install standalone配置1.使用当前项目的Django shell。 用于在同一Django项目中的...
VMware vCenter Converter Standalone Installer for Windows
django-models-standalone 这只是django框架之上的包装程序包,它仅包含独立模块来创建django项目。如何1.安装django-models-standalone: python setup.py install 2.创建独立的Django模型项目: cd ~django-models...
tyrus-standalone-client-1.13.1.jar
一个将Python代码转换成Java代码的编译器,能够将自己用Python代码写的类库用...Jython环境安装包: http://search.maven.org/remotecontent?filepath=org/python/jython-standalone/2.7.0/jython-standalone-2.7.0.jar
jackrabbit-standalone-1.6.5.jar是webDav的支持jar包。
hive-jdbc-3.1.2-standalone适用于linux
挣点辛苦币下载东西,没办法 E:\code\keycloak-11.0.3\standalone\configuration\standalone.xml
jython-standalone-2.7.2.jar,java应用调用Python。
linux standalone.conf linux standalone.sh 的启动配置文件
VMware vCenter Converter standalone 6.2 guide 的最新英文版
mule-standalone ESB 企业服务总线的开发工具,欢迎大家使用
VMware Converter Standalone 6.1.1 P2V迁移Linux一例
5g-standalone-access-registrationflow.pdf5g-standalone-access-registrationflow.pdf5g-standalone-access-registrationflow.pdf5g-standalone-access-registrationflow.pdf5g-standalone-access-...
jython-standalone-2.7.0.jar,和jython-standalone-2.7.0.jar源码
hive-jdbc-2.3.7-standalone,可用dbeaver连接hive数据库,在工具中进行数据库记录的新增改查
selenium-server-standalone-2.40.0.jar 、selenium-java-2.40.0-srcs.jar 、selenium-java-2.40.0.jar