使用Django commands构建命令行做定时(crontab)任务

需求: 我想调用django里models.py或者views.py的函数对数据库做些增删改查的操作,可以加入crontab做管理,找了半天才发现可以用django commands来搞,就简单记录下来怎么用。

这个app的内容如下:

tree weblog/
weblog/
├── __init__.py
├── __init__.pyc
├── admin.py
├── admin.pyc
├── apps.py
├── management
│   ├── __init__.py
│   ├── __init__.pyc
│   └── commands
│       ├── __init__.py
│       ├── __init__.pyc
│       ├── delete_author.py
│       └── delete_author.pyc
├── migrations
│   ├── 0001_initial.py
│   ├── 0001_initial.pyc
│   ├── __init__.py
│   └── __init__.pyc
├── models.py
├── models.pyc
├── tests.py
└── views.py

3 directories, 19 files

简单写一个函数,功能是删除weblog_author表的一条记录:

cat weblog/management/commands/delete_author.py
from django.core.management.base import BaseCommand, CommandError
from weblog.models import Author

class Command(BaseCommand):
    help = 'delete author'

    def add_arguments(self, parser):
        parser.add_argument('author_id',, type=int)

    def handle(self, *args, **options):
        for author_id in options['author_id']:
            try:
                author = Author.objects.get(pk=author_id)
            except Author.DoesNotExist:
                raise CommandError('Author "%s" does not exist' % author_id)

            author.delete()

            self.stdout.write(self.style.SUCCESS('Successfully delete author "%s"' % author_id))

执行

python manage.py delete_author  2
Successfully delete author “2"

加入到crontab里:

*/15 * * * * python /var/www/poll_mysite/manage.py delete_author  2 >/dev/null 2>&1
标签:Crontab 发布于:2019-11-13 20:17:59