最近想在django中写一些定时任务,期望能通过脚本运行,我们知道,django中有:
1 | $ django - admin.py [options] |
2 | $ python manage.py [options] |
而且django自带了非常多的默认命令,such as:
python manage.py startapp myapp
python manage.py runserver
python manage.py syncdb
然而,有时我们希望自定义commands,django是支持我们这么做的,这样的好处是我们可以直接使用项目的依赖关系和django。
1 创建形如下面的结构:
写道
myapp/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
mycommand.py
tests.py
views.py
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
mycommand.py
tests.py
views.py
编辑mycommand.py
from django.core.management.base import BaseCommand, CommandError
from django.db import models
import os
class Command(BaseCommand):
def handle(self, *args, **options):
print 'hello, django!'
加入到settings的INSTALLED_APPS
INSTALLED_APPS = (
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.messages",
"django.contrib.admin",
"duitang.hello",
#'sentry.client',
)
参考:http://blog.libears.com/2011-07-09/python/django-%E8%87%AA%E5%AE%9A%E4%B9%89django-admin-commands
http://www.cnblogs.com/holbrook/archive/2012/03/09/2387679.html
注意:目录必须包含__init__.py文件,不然不能识别命令