Django -commands

Django-Commands

2017-09-02 23:59:07
my site
code.python

. command 位置

Django 對於命令的添加有一套規範,你能夠爲每一個app 指定命令,對於代碼的放置位置他有規定的方式(固然你能夠hack 源碼)mysql

  1. 假如你新建了一個app 名字爲demogit

  2. 在demo 下新建一個python package 名稱必須爲management,github

  3. 在management 新建command 文件夾,sql

  4. 在command 下你就能夠構建本身的命令代碼shell

  5. 當以上工做完成是你的文件夾結構應該是: app/management/management/數據庫

.源碼解析

位置: core/management/__init__.pydjango

在這個文件中定義了加載命令的順序以及方式app

def find_commands(management_dir: "Users/fiz/Documents/py/demo/mycommand/management"):
    """
    Given a path to a management directory, return a list of all the command
    names that are available.
    """
    # 並在該文件下面查找commands 的路徑
    command_dir = os.path.join(management_dir, 'commands')
    #循環遍歷讀取文件下的Command
    return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])
            if not is_pkg and not name.startswith('_')]
@functools.lru_cache(maxsize=None)
def get_commands():
    # 加載全部內置的模塊定義的command
    commands = {name: 'django.core' for name in find_commands(__path__[0])}

    if not settings.configured:
        return commands
    # 循環讀取添加在install-app下的app 並查找commands的定義
    for app_config in reversed(list(apps.get_app_configs())):
        # 在當前路徑下尋找management文件夾
        path = os.path.join(app_config.path, 'management')
        commands.update({name: app_config.name for name in find_commands(path)})

    return commands

示範代碼

  1. 咱們添加一個爲備份數據庫的命令,運行這個命令能夠dump 數據庫到指定的文件中(相似mysqldump)ide

# -*- coding:utf-8 -*-
"""FIZ 17/9/2 """
import subprocess

from django.core.management.base import BaseCommand
from django.conf import settings


class Command(BaseCommand):
    """dump the database for backup"""
    help = ("dump the database for backup"
            "the deault db name is setting`s db name")
    requires_migrations_checks = True
    requires_system_checks = True

    def add_arguments(self, parser):
        parser.add_argument(
            '--database', action='store', dest='database', default=settings.DATABASES.get('default')
                .get('NAME'),
            help='provider a database for dump.',
        )
        parser.add_argument(
            '--file_name', action="store", dest="file_name", default='back.sql',
            help='save the db file'
        )

    def handle(self, *args, **options):
        database = options['database']
        print(database)
        file_name = options['file_name']
        pwd = settings.DATABASES.get('default').get("PASSWORD")
        try:

            subprocess.run(args=("mysqldump -u root -p{pwd}  {database}  ".format(
                database=database, pwd=pwd)),
                stdout=open(file_name, 'w+'),
                shell=True,
                check=True)
        except (Exception, EOFError) as info:
            print(info)

結果

Mou icon

Mou icon

Mou icon

:聽着李志的熱河,蠻不錯

若是年輕時你沒來過熱河路,

那你如今的生活是否是很幸福

記念碑旁有一家破舊的電影院,

往北走五百米就是南京火車西站

相關文章
相關標籤/搜索