Command Line execution of django source code (2.0.2), django2.0.2

Source: Internet
Author: User

Command Line execution of django source code (2.0.2), django2.0.2

Preface

 

The django command line is frequently used in the whole django web development and must be used. Therefore, it is very helpful to understand the command line implementation of django.

If you are concerned about the detailed description and use of django commands, you can view them here.

 

Command Line execution entry

 

Django uses django-admin.py and manage. py to execute commands. The following is the source code of these two files:

1 from django.core import management2 3 if __name__ == "__main__":4     management.execute_from_command_line()

They all call the execute_from_command_line () method under the management module.

This method is defined in django/core/management/_ init _. py:

1 def execute_from_command_line(argv=None):2     """Run a ManagementUtility."""3     utility = ManagementUtility(argv)4     utility.execute()

Implementation is very simple: generate a ManagementUtility object and run the corresponding command line command on this object. Therefore, the main work is implemented in the ManagementUtility class.

 

ManagementUtility class

 

Python is an object-oriented language. As a famous web framework of python, django is also an object-oriented idea. Therefore, when analyzing the source code, we should try to use the object-oriented thinking.

ManagementUtility has three attributes. We can see from its _ init _ function.

 

1 def _ init _ (self, argv = None): 2 self. argv = argv or sys. argv [:] # obtained from the input parameter. If no input parameter is input, it is obtained from sys. 3 self in argv. prog_name = OS. path. basename (self. argv [0]) 4 if self. prog_name = '_ main __. py': 5 self. prog_name = 'python-m django '6 self. settings_exception = None

Self. argv: command line information, including commands and Parameters

Self. prog_name: program name

Self. settings_excepiton: settings exception information. If the settings are abnormal, the exception information will be included in this variable.

 

The main method of ManagementUtility is execute (), which completes all the processes of command execution.

1. We know that the command line of django has a certain format, and both are command subcommand [arguments]. arguments is sometimes optional. Therefore, the first step of the execute method is to obtain the subcommand to determine the subsequent tasks.

 

1         try:2             subcommand = self.argv[1]3         except IndexError:4             subcommand = 'help'  # Display help if no arguments were given.    

Here, why not get the command first? In fact, the command is used by the system to find the program entry.

2. Use the command parser CommandParser to parse the command line. CommandParser inherits the ArgumentParser class of the argparse module, but it only strengthens the Exception Handling of ArgumentParser.

 

 1 class CommandParser(ArgumentParser): 2     """ 3     Customized ArgumentParser class to improve some error messages and prevent 4     SystemExit in several occasions, as SystemExit is unacceptable when a 5     command is called programmatically. 6     """ 7     def __init__(self, cmd, **kwargs): 8         self.cmd = cmd 9         super().__init__(**kwargs)10 11     def parse_args(self, args=None, namespace=None):12         # Catch missing argument for a better error message13         if (hasattr(self.cmd, 'missing_args_message') and14                 not (args or any(not arg.startswith('-') for arg in args))):15             self.error(self.cmd.missing_args_message)16         return super().parse_args(args, namespace)17 18     def error(self, message):19         if self.cmd._called_from_command_line:20             super().error(message)21         else:22             raise CommandError("Error: %s" % message)

 

Argparse official document | argparse usage Summary

3. the parser parses the arguments of the subcommand, and then fetch_command imports the corresponding command package according to the subcommand and generates the corresponding command object, call the print_help method or run_from_argv method of the command object to execute the corresponding command.

 1         if subcommand == 'help': 2             if '--commands' in args:    # only print the commands only 3                 sys.stdout.write(self.main_help_text(commands_only=True) + '\n') 4             elif len(options.args) < 1: # print out the usages 5                 sys.stdout.write(self.main_help_text() + '\n') 6             else:  7                 self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0]) 8         # Special-cases: We want 'django-admin --version' and 9         # 'django-admin --help' to work, for backwards compatibility.10         elif subcommand == 'version' or self.argv[1:] == ['--version']:11             sys.stdout.write(django.get_version() + '\n')12         elif self.argv[1:] in (['--help'], ['-h']):13             sys.stdout.write(self.main_help_text() + '\n')14         else:15             self.fetch_command(subcommand).run_from_argv(self.argv)        

Finally, let's take a look at the fetch_command code:

 1     def fetch_command(self, subcommand): 2         """ 3         Try to fetch the given subcommand, printing a message with the 4         appropriate command called from the command line (usually 5         "django-admin" or "manage.py") if it can't be found. 6         """ 7         # Get commands outside of try block to prevent swallowing exceptions 8         commands = get_commands() 9         try:10             app_name = commands[subcommand]11         except KeyError:12             if os.environ.get('DJANGO_SETTINGS_MODULE'):13                 # If `subcommand` is missing due to misconfigured settings, the14                 # following line will retrigger an ImproperlyConfigured exception15                 # (get_commands() swallows the original one) so the user is16                 # informed about it.17                 settings.INSTALLED_APPS18             else:19                 sys.stderr.write("No Django settings specified.\n")20             sys.stderr.write(21                 "Unknown command: %r\nType '%s help' for usage.\n"22                 % (subcommand, self.prog_name)23             )24             sys.exit(1)25         if isinstance(app_name, BaseCommand):26             # If the command is already loaded, use it directly.27             klass = app_name28         else:29             klass = load_command_class(app_name, subcommand)30         return klass

Load_command_class is used to import the corresponding subcommand module and generate a command class object.

1 def load_command_class(app_name, name):2     """3     Given a command name and an application name, return the Command4     class instance. Allow all errors raised by the import process5     (ImportError, AttributeError) to propagate.6     """7     module = import_module('%s.management.commands.%s' % (app_name, name))8     #print("import %s %s" %(app_name, name))9     return module.Command()

You can take a look at a command module in the django/core/management/command/directory. For example, check. py. Each module has a command class inherited from BaseCommand. The print_help method or run_from_argv method mentioned above are implemented in the BaseCommand class.

1 class Command(BaseCommand):2     help = "Checks the entire Django project for potential problems."3 4     requires_system_checks = False5     6     #...

 

 

-------------------------------------------------

The above is my rough understanding. If you find anything wrong, please give me some advice. Thank you very much!

17:57:17

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.