Django 添加自定义命令

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

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

所以我们就来讲讲如何自定义扩展manage命令。

源码分析

manage.py 文件是通过 django-admin startproject project_name 生成的。

  1. manage.py的源码

    • 首先设置了 settings 文件

    • 其次执行了一个函数django.core.management.execute_from_command_line(sys.argv),这个函数传入了命令行参数 sys.argv

      #!/usr/bin/env python
      import os
      import sys
          
      if __name__ == "__main__":
          os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CIServer.settings")
          try:
              from django.core.management 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?"
              )
          execute_from_command_line(sys.argv)
      
  2. execute_from_command_line

    里面调用了ManagementUtility类中的execute方法

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

    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
        calls.
        """
        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: app_config.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('_')]
    

    可以发现并注册的命令是commands目录下不以"_"开头的文件名。

  4. load_command_class

    将命令文件***.py中的Command类加载进去。

    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('%s.management.commands.%s' % (app_name, name))
        return module.Command()
    
  5. Command

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

具体实现

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

(python3) ➜  blog tree   
.
├── __init__.py
└── management
    ├── __init__.py
    └── commands
        ├── __init__.py 
        └── ping_baidu.py

ping_baidu.py 中实现命令的具体内容

from django.core.management.base 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'):
                urls.append(article.get_full_url())
        if type == 'tag' or type == 'all':
            for tag in Tag.objects.all():
                url = tag.get_absolute_url()
                urls.append(self.get_full_url(url))
        if type == 'category' or type == 'all':
            for category in Category.objects.all():
                url = category.get_absolute_url()
                urls.append(self.get_full_url(url))

        self.stdout.write(self.style.SUCCESS('start notify %d urls' % len(urls)))
        notify.baidu_notify(urls)
        self.stdout.write(self.style.SUCCESS('finish notify'))

sipder_notify.py 也很简单:

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


class SpiderNotify():
    //提交百度统计
    @staticmethod
    def baidu_notify(urls):
        try:
            data = '\n'.join(urls)
            result = requests.post(settings.BAIDU_NOTIFY_URL, data=data)
            print(result.text)
        except Exception as e:
            print(e)
    //熊掌号接入
    @staticmethod
    def baidu_bear_notify(urls):
        try:
            data = '\n'.join(urls)
            result = requests.post(settings.BAIDU_BEAR_NOTIFY_URL, data=data)
            print(result.text)
        except Exception as e:
            print(e)
    //提交到谷歌
    @staticmethod
    def __google_notify():
        try:
            ping_google('/sitemap.xml')
        except Exception as e:
            print(e)

    @staticmethod
    def notify(url):

        SpiderNotify.baidu_notify(url)
        SpiderNotify.__google_notify()
        SpiderNotify.baidu_bear_notify(url)    

至此,基本都完成了,可以终端执行./manage.py查看输出:

(python3) ➜  DjangoBlog ./manage.py 

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

Available subcommands:

[auth]
    changepassword
    createsuperuser

[blog]
    ping_baidu

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

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

notify baidu url

positional arguments:
  {all,article,tag,category}
                        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
                        used.
  --pythonpath PYTHONPATH
                        A directory to add to the Python path, e.g.
                        "/home/djangoprojects/myproject".
  --traceback           Raise on CommandError exceptions
  --no-color            Don't colorize the command output.

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

此文章同时同步到我的个人博客緣來來來 » Django 添加自定义命令](https://www.fkomm.cn/article/2018/10/17/55.html)

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容