Django command execution script

Scripts are often used in python web projects. Generally speaking, there are two very simple methods, one is direct python function, and the other is django custom command.

vs regular script

Here is a simple example, such as initializing data and the file name is initialize_data.py

(1) Usage method 1:

from django.utils import timezone
from your_app.models import Your_model

def initialize_data():
    unit_data = [
        {
            'name': 'Tom',
            'age': 12,
        },
        {
            'name': 'Jerry',
            'age': 23,
        }
    ]

    Your_model.objects.bulk_create(Your_model(**data))

# 调用初始化函数
initialize_data()

(2) Use method 2 (recommended for web development), use BaseCommand (use from django.core.management.base import BaseCommand to create a custom Django management command to better organize and manage scripts):

from django.core.management.base import BaseCommand
from django.utils import timezone
from your_app.models import Your_model

class Command(BaseCommand):
    help = 'Initialize data'

    def handle(self, *args, **options):
        unit_data = [
            {
                'name': 'Tom',
                'age': 12,
            },
            {
                'name': 'Jerry',
                'age': 23,
            }
        ]
        Your_model.objects.bulk_create(Your_model(**data))

By inheriting the BaseCommand class and implementing the handle method, we can place the script logic in the handle method. We can then execute the command by runningpython manage.py initialize_data on the command line.

Advantage:

  1. Better organization and management: UseBaseCommand to encapsulate script logic into a custom Django management command, making the code more modular and maintainable.
  2. Supports command line parameters:BaseCommand provides the function of processing command line parameters, and can pass parameters to the script through the command line.
  3. Integrated Django environment: UseBaseCommand to directly access Django's models and other functions without additional configuration.

Disadvantages:

  1. Needs to create a management command: Compared with running the script file directly, usingBaseCommand requires creating a custom management command and running the command in the command line.


Command line parameters

Let’s talk about the command line parameters here.

Note: The Command class name is a convention for custom management commands, but you can choose another name, just make sure to inherit from the BaseCommand class That's it

from django.core.management.base import BaseCommand
from your_app.models import YourModel

class Command(BaseCommand):
    help = 'Initialize data'

    def add_arguments(self, parser):
        parser.add_argument('--name', type=str, help='Set name value')
        parser.add_argument('--age', type=int, help='Set age value')

    def handle(self, *args, **options):
        name = options['name']
        age = options['age']

        if name and age:
            YourModel.objects.create(name=name, age=age)
        else:
            self.stdout.write(self.style.ERROR('Please provide both name and age values.'))

Run the following command to create it:

python manage.py initialize_data --name Tom --age 1

        Use theadd_arguments method to define command line parameters. In this example, two parameters --name and --age are added to set name and method, we get the values ​​of the command line parameters through and , and create instance. agehandleoptions['name']options['age']YourModel

other

When executing scripts, you often need to pay attention to security and scalability.

        (1) Security, such as batch modification and multi-table modification of information. At this time, transactions need to be added to ensure data security; at the same time, pay attention to exception capture and print log checks;

        (2) Scalability. When writing scripts, we often hope that they can be subsequently expanded and usable. Command line parameters can achieve this property.

        

Guess you like

Origin blog.csdn.net/lxd_max/article/details/134464829