Django 添加自定义命令

使用Django开发,对 python *** 命令模式肯定不会陌生。比较常用的有 runservermigrate等!

有时候会有这样的需求,为 Django 执行一些定时任务,比如通知搜索引擎,例如百度,提交网站的一些地址给他们,则可以通过为 添加自定义命令可以很容易的解决这个问题。


源码分析 文件是通过 django-admin startproject project_name 生成的。

  1. manage.py的源码

    • 首先设置了 settings 文件
    • 其次执行了一个函数,这个函数传入了命令行参数 sys.argv

      #!/usr/bin/env python
      import os
      import sys
      if __name__ == "__main__":
         os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CIServer.settings")
             from import execute_from_command_line
         except ImportError:
            raise ImportError(
                 "Couldn't import Django. Are you sure it's installed and available "
                 "on your PATH environment variable? Did you forget to activate a "
                 "virtual environment?"
  2. execute_from_command_line


    def execute_from_command_line(argv=None):
       A simple method that runs a ManagementUtility.
       utility = ManagementUtility(argv)

    execute 中主要是解析了传入的参数 sys.argv ,并且调用了get_command()

  3. get_command

    def get_commands():
       Returns a dictionary mapping command names to their callback applications.
       This works by looking for a management.commands package in django.core, and
      in each installed application -- if a commands package exists, all commands
      in that package are registered.
       Core commands are always included. If a settings module has been
       specified, user-defined commands will also be included.
       The dictionary is in the format {command_name: app_name}. Key-value
      pairs from this dictionary can then be used in calls to
      load_command_class(app_name, command_name)
       If a specific version of a command must be loaded (e.g., with the
      startapp command), the instantiated module can be placed in the
      dictionary in place of the application name.
       The dictionary is cached on the first call and reused on subsequent
       commands = {name: 'django.core' for name in find_commands(upath(__path__[0]))}
       if not settings.configured:
          return commands
       for app_config in reversed(list(apps.get_app_configs())):
          path = os.path.join(app_config.path, 'management')
           commands.update({name: for name in find_commands(path)})
       return commands

    get_command 里遍历所有注册的 INSTALLED_APPS 路径下的management 寻找 (find_commands) 用户自定义的命令。

    def find_commands(management_dir):
       Given a path to a management directory, returns a list of all the command
      names that are available.
       Returns an empty list if no commands are defined.
       command_dir = os.path.join(management_dir, 'commands')
       # Workaround for a Python 3.2 bug with pkgutil.iter_modules
      sys.path_importer_cache.pop(command_dir, None)
       return [name for _, name, is_pkg in pkgutil.iter_modules([npath(command_dir)])
               if not is_pkg and not name.startswith('_')]


  4. load_command_class


    def load_command_class(app_name, name):
       Given a command name and an application name, returns the Command
      class instance. All errors raised by the import process
      (ImportError, AttributeError) are allowed to propagate.
       module = import_module('' % (app_name, name))
       return module.Command()
  5. Command

    Command 类要继承 BaseCommand 类,其中很多方法,一定要实现的是 handle 方法,handle 方法是命令实际执行的代码。


根据上面说的原理,我们只需要在创建好的应用的根目录创建文件夹名为 management 的目录,然后继续在该目录创建 commands 的目录,并在两个目录中都要创建 的 python 文件。 目录创建好之后继续在commands 的目录中添加 文件,文件名将会是 的命令名. 目录结构如下:

(python3) ➜  blog tree   
└── management
    └── commands
        └── 中实现命令的具体内容

from import BaseCommand, CommandError
from blog.models import Article, Tag, Category
from DjangoBlog.spider_notify import sipder_notify
from django.contrib.sites.models import Site

site = Site.objects.get_current().domain

class Command(BaseCommand):
    help = 'notify baidu url'

    def add_arguments(self, parser):
        parser.add_argument('data_type', type=str, choices=['all', 'article', 'tag', 'category'],
                            help='article : all article,tag : all tag,category: all category,all: All of these')

    def get_full_url(self, path):
        url = "https://{site}{path}".format(site=site, path=path)
        return url

    def handle(self, *args, **options):
        type = options['data_type']
        self.stdout.write('start get %s' % type)
        notify = sipder_notify()
        urls = []
        if type == 'article' or type == 'all':
            for article in Article.objects.filter(status='p'):
        if type == 'tag' or type == 'all':
            for tag in Tag.objects.all():
                url = tag.get_absolute_url()
        if type == 'category' or type == 'all':
            for category in Category.objects.all():
                url = category.get_absolute_url()

        self.stdout.write('start notify %d urls' % len(urls)))
        self.stdout.write('finish notify')) 也很简单:

from django.contrib.sitemaps import ping_google
import requests
from django.conf import settings

class SpiderNotify():
    def baidu_notify(urls):
            data = '\n'.join(urls)
            result =, data=data)
        except Exception as e:
    def baidu_bear_notify(urls):
            data = '\n'.join(urls)
            result =, data=data)
        except Exception as e:
    def __google_notify():
        except Exception as e:

    def notify(url):



(python3) ➜  DjangoBlog ./ 

Type ' help <subcommand>' for help on a specific subcommand.

Available subcommands:



可以看到 ping_baidu 命令已经出现了,./ ping_baidu --help 可以查看帮助:

(python3) ➜  DjangoBlog ./ ping_baidu --help
usage: ping_baidu [-h] [--version] [-v {0,1,2,3}]
                            [--settings SETTINGS] [--pythonpath PYTHONPATH]
                            [--traceback] [--no-color]

notify baidu url

positional arguments:
                        article : all article,tag : all tag,category: all
                        category,all: All of these

optional arguments:
  -h, --help            show this help message and exit
  --version             show program's version number and exit
  -v {0,1,2,3}, --verbosity {0,1,2,3}
                        Verbosity level; 0=minimal output, 1=normal output,
                        2=verbose output, 3=very verbose output
  --settings SETTINGS   The Python path to a settings module, e.g.
                        "myproject.settings.main". If this isn't provided, the
                        DJANGO_SETTINGS_MODULE environment variable will be
  --pythonpath PYTHONPATH
                        A directory to add to the Python path, e.g.
  --traceback           Raise on CommandError exceptions
  --no-color            Don't colorize the command output.

最后在终端执行: ./ ping_baidu all 即可。