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
1 http://www.baidu.com
2 http://www.qq.com
api_urls

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM