Django 源碼閱讀

      週末無聊沒事作又不想看電影了, 最近恰好學了一下python 而且用django 寫了一個公司簽到的打卡展現系統。想一想就看看django源碼好了。 不知道能堅持看多久。記錄下python

      1. 先從github上fork一個。並把fork後的代碼弄到本地工程裏面。 如今最新的是1.9.4了。 我直接fork mastergit

       效果:github

             

    總目錄下有個__main__.py 應該是比較重要的文件了。點進去sql

  

"""
Invokes django-admin when the django module is run as a script.

Example: python -m django check

"""
from django.core import management

if __name__ == "__main__":
    management.execute_from_command_line()

     註釋上寫: 當django module 以腳本形式運行是調用django-admin  (好吧不太懂)shell

 直接看看 execute_from_command_line 函數作了什麼django

  

def execute_from_command_line(argv=None):
    """
    A simple method that runs a ManagementUtility.
    """
    utility = ManagementUtility(argv)
    utility.execute()

  新建一個管理工具類。app

  類太多不貼了 貼個地址 ManagementUtility函數

  到execute 方法裏面
工具

 def execute(self):
        """
        Given the command-line arguments, this figures out which subcommand is
        being run, creates a parser appropriate to that command, and runs it.
        """
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None, usage="%(prog)s subcommand [options] [args]", add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        no_settings_commands = [
            'help', 'version', '--help', '--version', '-h',
            'compilemessages', 'makemessages',
            'startapp', 'startproject',
        ]

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
            # A handful of built-in management commands work without settings.
            # Load the default settings -- where INSTALLED_APPS is empty.
            if subcommand in no_settings_commands:
                settings.configure()

        if settings.configured:
            # Start the auto-reloading dev server even if the code is broken.
            # The hardcoded condition is a code smell but we can't rely on a
            # flag on the command class because we haven't located it yet.
            if subcommand == 'runserver' and '--noreload' not in self.argv:
                try:
                    autoreload.check_errors(django.setup)()
                except Exception:
                    # The exception will be raised later in the child process
                    # started by the autoreloader. Pretend it didn't happen by
                    # loading an empty list of applications.
                    apps.all_models = defaultdict(OrderedDict)
                    apps.app_configs = OrderedDict()
                    apps.apps_ready = apps.models_ready = apps.ready = True

            # In all other cases, django.setup() is required to succeed.
            else:
                django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(self.main_help_text(commands_only=True) + '\n')
            elif len(options.args) < 1:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)

 如今明白了註釋裏面的內容了測試

好如今咱們能夠測試一下:

      直接運行__main__.py 這個文件。。 好出錯了。 包沒有導入。

      難不倒我, 註釋上不是說是django-admin 嗎。 我打開bin 目錄下的那個django-admin.py . 原來跟這個__main__.py 寫的同樣的。 運行一下試試。

   

Type 'django-admin.py help <subcommand>' for help on a specific subcommand.

Available subcommands:

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    runserver
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver
Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.).

  仔細閱讀一下 裏面能夠輸入不少參數。

 試一下加個參數 management.execute_from_command_line(['','version']) 。 (這裏稍微說明一下, 函數裏面能夠看到 它取的是第二個參數。第一個參數忽略了。 其實若是從命令行輸入的話第一個參數是文件名)

 也成功輸入了 verison


今天就看到這。 其餘的參數要配置一下環境了。

相關文章
相關標籤/搜索