Django source code reading and analysis-1: command line option

Source: Internet
Author: User

Disclaimer: This article is reprinted

Start a project with Django, probably using commands. You can use it to create a project, clean up the project, and enter the interactive environment. I want to know about Django and how to use python to build an excellent project and framework. Since I used django1.1.1 in the project, I used this version as the blueprint. So far, Django has been upgraded to version 1.2.1.

First, let's take a lookSource codeDirectory structure. For more information, see its structure. There are a lot of things that are unclear to me now, and there may be a lot of inaccuracies in my understanding, so I can correct them at any time.

    • -Bin // the executable file, Django's path can be set here, and one of our most commonly used commands is the in it
    • -Conf // This is a configuration file for the generated project and app, including the python file that will be copied to the project or appCodeTemplate.
    • -Contrib // standard module. That is to say, you can survive without it. With it, you can reduce your workload. For example, a common admin background, User Authentication Component, session, site map, and so on.
    • -Core // Core Module
    • -DB // database interface. Django can be compatible with many databases, including MySQL, Oracle, and SQLite. DB also includes the definition of the data model. Using these definitions can shield the differences between the underlying dnms.
    • -Dispatch // signal-related Module
    • -Froms // form processing module
    • -Http // HTTP request and response
    • -Middleware // middleware. It can help the system to execute some processing before processing the request.
    • -Shortcuts // shortcut, for example, the commonly used render_to_response method is here.
    • -Template and templatetags // Django template engine
    • -Test // unit test framework
    • -Utils // small utilityProgram
    • -Views // view processing


After installing Django from the source code using the python setup. py install command, these will be copied to the LIB/Site-packages/Django subdirectory under the python installation directory. The first command we use Django is probably to use the startproject projectname to create a project, and I plan to start from here. commands can be written in Django using a series of arguments corresponding to the command. core. management. in the commands namespace, you can see many modules. Each module is a parameter corresponding to the Django-admin command.

    1. Command Line call command subcommand [Options] [ARGs]
    2. Initialize managementutil and call its execute () method.
    3. Parse and verify the parameters, and call the fetch_command () method to obtain the corresponding command
    4. According to the model corresponding to the import parameter, the import operation uses the built-in Python _ import __
    5. Call the basecommand. run_from_argv () method in the core. Management. Base. py module.
    6. Run_from_argv () method call create_parser () to create a parser, parse parameters and configure the environment, and then call the execute () method
    7. The execute () method calls the handle () method to execute the command. The implementation of the handle () method in the basecommand class simply throws an exception, therefore, each sub-class of basecommand must overwrite this method to use this command.

Features: Implemented in command mode.


Select a command to see how it is implemented. Take the startproject. py command, which is one of the simplest.

Class command (labelcommand): Help = "creates a Django project directory structure for the \ Given Project name in the current directory. "ARGs =" [projectname] "label = 'Project name' requires_model_validation = false # Can't import settings during this command, because they haven't# necessarily been created. can_import_settings = false def handle_label (self, project_name, ** options): # determine t He project_name a bit naively -- by looking at the name of # The parent directory. directory = OS. getcwd () # check that the project_name cannot be imported. try: import_module (project_name) failed t importerror: Pass else: Raise commanderror ("% R conflicts with the name of an existing Python module \ and cannot be used as a project name. please try another name. "% project_name) copy_helper (self. styl E, 'project_name, directory) # create a random secret_key hash, and put it in the main settings. main_settings_file = OS. path. join (directory, project_name, 'settings. py') settings_contents = open (main_settings_file, 'R '). read () fp = open (main_settings_file, 'w') secret_key = ''. join ([choice ('abcdefghijklmnopqrstuvwxyz \ 0123456789! @ # $ % ^ & * (-_ = +) ') For I in range (50)]) settings_contents = Re. sub (R "(? <= Secret_key = ')' ", secret_key +" '", settings_contents) FP. Write (settings_contents) FP. Close ()

This is a subclass of labelcommand. There is only one method: handle_label (). The implementation of the labelcommand class already overwrites the basecommand handle () method, but exposing this handle_label () still throws an exception and requires its subclass to implement it.

Class labelcommand (basecommand): ARGs =''Label = 'label' def handle (self, * labels, ** options): If not labels: Raise commanderror ('enter at least one % S. '% self. label) Output = [] for label in labels: label_output = self. handle_label (Label, ** options) If label_output: output. append (label_output) return '\ n '. join (output) def handle_label (self, label, ** options): "perform the command's actions for ''label '', which will be the string as given on the command line. "" Raise notimplementederror ()

We can see that handle_label () in the startproject. py command has two things:

    1. Copy the files in the corresponding template directory to the project directory with the specified name.
    2. Generate a random secret_key hash value.

This Is What Django did for us when we started a project, which is very simple. Of course, when you start the server, there will be more complex operations, which are also implemented through a series of commands. Let's look back at the level chart of the command:


There are three types of commands: app commands, tag commands, and no-argument commands.

    • APP command: used to maintain the app. If it inherits from basecommand, the handle () method must be implemented. If it inherits from appcommand, The handle_app () method must be implemented;
    • Tag command: Contains parameters. For example, startproject is a tag command and the parameter is the name of the project you want to create. The handle () or handle_label () method must be implemented;
    • Argument-free command: This command does not require any parameters. An example is the validate command used to verify the model.




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: 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.