2017-09-02 23:59:07
my site
code.python
Django 对于命令的添加有一套规范,你能够为每一个app 指定命令,对于代码的放置位置他有规定的方式(固然你能够hack 源码)mysql
假如你新建了一个app 名字为demogit
在demo 下新建一个python package 名称必须为management,github
在management 新建command 文件夹,sql
在command 下你就能够构建本身的命令代码shell
当以上工做完成是你的文件夹结构应该是: 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
咱们添加一个为备份数据库的命令,运行这个命令能够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)
若是年轻时你没来过热河路,
那你如今的生活是否是很幸福
记念碑旁有一家破旧的电影院,
往北走五百米就是南京火车西站