Django 自定义command调用 call_command多参数

2022-08-12 16:54:23 浏览数 (1)

想解决的课题内容

  • 自定义command
  • command 通常用cli执行,代码中调用使用 call_command(name, *args, **options)
  • customize command多参数写法 call_command('create_user', 'username=u001', '--password=12345678')

自定义command及其调用

自定义command

在应用程序中添加一个management/commands目录。Django 会给目录下的每个 Python 模块注册一个manage.py命令,这个命令的名字不以下划线开头。

代码语言:python代码运行次数:0复制
core/
    __init__.py
    management/commands/    # 文件夹路径是必须的
        __init__.py
        create_user.py      # 创建用户(指定登录值)
        create_admin.py     # 创建系统管理员用户
        create_testuser.py  # 创建用户,并赋予权限 (调用create_user.py)
代码语言:python代码运行次数:0复制
create_user.py

from django.core.management.base import BaseCommand
from django.contrib.auth.models import User

class Command(BaseCommand):
    help = "create user"

    # 参数设定
    def add_arguments(self , parser):
        parser.add_argument('username',  nargs=' ', type=str) # 必须项目
        parser.add_argument('--password', nargs='?', type=str) # 任意项目
        parser.add_argument('--email', action='append', type=str)  # 任意项目

    def handle(self, *args, **options):
        user = User()

        username  = options['username']
        password  = options['password']
        email     = options['email']

        user.username = username[0]
        user.set_password(password[0])
        if email:
            user.email = email[0]

        user.save()

执行命令:python manage create_user username admin002 --password 12345678 --email admin002@email.com

代码语言:python代码运行次数:0复制
create_admin.py

class Command(BaseCommand):
    help = "create admin user"

    @transaction.atomic
    def handle(self, *args, **options):
        u=User()
        u.username = 'admin'
        u.password = '12345678'
        u.save()
        後略

执行命令:python manage create_admin

parse nargs

parse action

查看自定义command(Available subcommands)

python manage.py help

自定义command 在对应app下显示

※若自定义的command没有在列表中表示,则可能是【management>commands】文件夹阶层不对,或者是新作成的app,没有追加到setting.py>INSTALLED_APPS 中

代码语言:python代码运行次数:0复制
(venv) PS D:PycharmProjectspj> python manage.py help

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

Available subcommands:

[auth]
    changepassword
    createsuperuser

[contenttypes]
    remove_stale_contenttypes

[core]                    # 自定义command 在对应app下显示 
    create_testuser
    create_user
    createadmin
[django]
    makemessages
    makemigrations
    migrate
    sendtestemail
    squashmigrations
    startapp
    startproject
    test
    testserver

[sessions]
    clearsessions

[staticfiles]
    collectstatic
    findstatic
    runserver

command执行方法

  1. 终端敲命令
  2. 代码中调用,call_command

终端执行:

有参数:python manage create_user username admin002 --password 12345678 --email admin002@email.com

无参数:python manage create_admin

若传参有误,log会提示,按照提示,输入参数即可,例:

代码语言:javascript复制
(smsenv) PS D:Projectspj> python .manage.py create_user username admin002 --password 12345678
usage: manage.py create_user [-h] [--firstname FIRSTNAME] [--lastname LASTNAME] [--password PASSWORD] [--email EMAIL] [--startdate STARTDATE] [--enddate ENDDATE]
                             [--department DEPARTMENT] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color]   
                             [--skip-checks]
                             username
manage.py create_user: error: unrecognized arguments: admin002

代码中调用,call_command

代码语言:python代码运行次数:0复制
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User, Group, Permission
from django.db import transaction

class Command(BaseCommand):
    help = "create test user"

    @transaction.atomic
    def handle(self, *args, **options):
        
        User.objects.all().delete()
        Role.objects.all().delete()
        Group.objects.all().delete()

        call_command('createadmin')   # 无参数的command调用

command多参数写法(call_command 複数引数, args, options

代码语言:python代码运行次数:0复制
    user_list = [
        ['username=u001', '--password=12345678', '--email=user001@gmail.com', ],
        ['username=u002', '--password=12345678', '--email=user002@gmail.com', ],
        ['username=u003', '--password=12345678', '--email=user003@gmail.com', ],
        ['username=u004', '--password=12345678', '--email=user004@gmail.com', ],
        ['username=u005', '--password=12345678', '--email=user005@gmail.com', ],
        ['username=u006', '--password=12345678', '--email=user006@gmail.com', ],
        ['username=u007', '--password=12345678', '--email=user007@gmail.com', ],
        ['username=u008', '--password=12345678', '--email=user008@gmail.com', ]
    ]

    for i in range(0,8):
        pay_dict = user_list[i]
    
        call_command('create_user',pay_dict)   # 传参

具体应用(作成user,role,permission)

要件:UT测试阶段需要,创建一些User,role,并按照式样,给相应的user赋予权限

测试数据设计测试数据设计
代码语言:python代码运行次数:0复制
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User, Group, Permission
from master.models import Role
from django.db import transaction
import logging

log = logging.getLogger(__name__)

class Command(BaseCommand):
    help = "create test user"

    @transaction.atomic
    def handle(self, *args, **options):

        User.objects.all().delete()
        Role.objects.all().delete()
        Group.objects.all().delete()

        call_command('createadmin')

        # ユーザー一覧 (create_user の引数)
        user_list = [
            ['username=u001', '--password=12345678', '--email=user001@gmail.com', ],
            ['username=u002', '--password=12345678', '--email=user002@gmail.com', ],
            ['username=u003', '--password=12345678', '--email=user003@gmail.com', ],
            ['username=u004', '--password=12345678', '--email=user004@gmail.com', ],
            ['username=u005', '--password=12345678', '--email=user005@gmail.com', ],
            ['username=u006', '--password=12345678', '--email=user006@gmail.com', ],
            ['username=u007', '--password=12345678', '--email=user007@gmail.com', ],
            ['username=u008', '--password=12345678', '--email=user008@gmail.com', ]
        ]

        # ロール作成
        role_list = [
            {'name':'role1'},
            {'name':'role2'},
            {'name':'role3'},
            {'name':'role4'},
            {'name':'role5'},
            {'name':'role6'},
            {'name':'role7'},
            {'name':'role8'}
        ]
        # ロール&権限 mapping
        g_mapping = [
            [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], # role1
            [ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 ], # role2
            [ 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 ], # role3
            [ 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 ], # role4
            [ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0 ], # role5
            [ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], # role6
            [ 1, 0, 1, 1, 1, 1, 0, 0, 1, 0 ], # role7
            [ 1, 0, 1, 1, 1, 1, 1, 1, 0, 0 ] # role8
        ]

        # 権限
        perms_list = [
            { 'position': 0, 'codename': 'perm1'},
            { 'position': 1, 'codename': 'perm2'},
            { 'position': 2, 'codename': 'perm3'},
            { 'position': 3, 'codename': 'perm4'},
            { 'position': 4, 'codename': 'perm5'},
            { 'position': 5, 'codename': 'perm6'},
            { 'position': 6, 'codename': 'perm7'},
            { 'position': 7, 'codename': 'perm8'},
            { 'position': 8, 'codename': 'perm9'},
            { 'position': 9, 'codename': 'perm10'}
        ]

        for i in range(0,8):
            pay_dict = user_list[i]
            
            call_command('create_user',pay_dict)

            # ユーザー取得
            log.info(pay_dict[0][-4:])
            u = User.objects.filter(username=pay_dict[0][-4:]).first()
            if u == None:
                pass
            g = Group()
            g.name = role_list[i]['name']
            r = Role()
            r.comment = role_list[i]['name']
            g.save()
            r.group = g
            r.save()
            
            for p in perms_list:
                try:
                    # log.info(g_mapping[i][p['position']])
                    # mappingより権限付与
                    if g_mapping[i][p['position']] == 1:
                        g.permissions.add(Permission.objects.filter(codename=p['codename']).first())
                except Permission.DoesNotExist as e:
                    pass
            
            u.groups.add(g)

#Django Customize command ,django.core.management.call_command(name, *args, **options)

#Django カスタマイズコマンドをコードから呼ぶ(引数 複数)

0 人点赞