Django commands自定制
什么是Django Commands
Django 对于命令的添加有一套规范,你可以为每个app 指定命令。通俗一点讲,比如在使用manage.py文件执行命令的时候,可以自定制自己的命令,来实现命令的扩充。
commands的创建
1、在app内创建一个management的python目录 2、在management目录里面创建commands的python文件夹 3、在commands文件夹下创建任意py文件
此时py文件名就是你的自定制命令,可以使用下面方式执行
python manage.py 命令名
撰写command文件要求
首先对于文件名没什么要求,内部需要定义一个Command类并继承BaseCommand类或其子类。
文件结构
其中help是command功能作用简介,handle函数是主处理程序,add_arguments函数是用来接收可选参数的
简单测试
# -*- coding: utf-8 -*- # __author__ = 'dandy' from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'test' def handle(self, *args, **options): print('test')
带参数的测试
# -*- coding: utf-8 -*- # __author__ = 'dandy' from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('aaa', nargs='+', type=int) parser.add_argument('--delete', action='store_true', dest='delete', default=False, help='Delete poll instead of closing it') def handle(self, *args, **options): print('test') print(args, options)
options里面直接取参数就可以了。
1 # -*- coding: utf-8 -*- 2 # __author__ = 'dandy' 3 from django.core.management.base import BaseCommand 4 from django.conf import settings 5 import requests 6 import os 7 import threading 8 9 command_path = os.path.join(settings.BASE_DIR, 'api', 'management', 'commands') 10 file = os.path.join(command_path, 'api_urls') 11 12 13 class Command(BaseCommand): 14 help = 'test cost time for each api when getting data .We have set a middleware and create a file for log.' \ 15 'here just send request by thread pool' 16 17 def handle(self, *args, **options): 18 url_list = [] 19 try: 20 if not os.path.exists(file): 21 raise FileNotFoundError('ERROR!!!! no file named api_urls in %s' % file) 22 with open (file, 'rb') as obj: 23 urls = obj.readlines() 24 if not len(urls): 25 raise Exception('ERROR!!! api_urls is a empty file !!') 26 for url in urls: 27 url = url.strip() 28 if url: 29 t = threading.Thread(target=self.get_url, args=(url,)) 30 # t.setDaemon(True) # set True and you don't need to wait until main thread finished 31 t.start() 32 print('send all request successfully !') 33 except Exception as e: 34 print(e) 35 36 def get_url(self, url): 37 requests.get(url)
1 http://www.baidu.com 2 http://www.qq.com