Django源码解读[1]

manage.py文件:

  import os
  import sys

  if __name__ == "__main__":
    print(__name__)#manage.py本身调用,那么会输出__main__
    print(os.path.abspath(__file__))#输出当前文件的绝对路径
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
    #If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
    print(os.environ.get('DJANGO_SETTINGS_MODULE'))#os.environ是个dict 输出mysite.settings
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            )
        raise
    execute_from_command_line(sys.argv)

execute_from_command_line实际执行的是django/core/management/__init__.py中的ManagementUtility.execute方法

    def execute_from_command_line(argv=None):

    """

       A simple method that runs a ManagementUtility.

     """

    utility = ManagementUtility(argv)

    utility.execute()
    class ManagementUtility(object):

"""

    Encapsulates the logic of the django-admin and manage.py utilities.

    A ManagementUtility has a number of commands, which can be manipulated

   by editing the self.commands dictionary.

 """

   def __init__(self, argv=None):

       self.argv = argv or sys.argv[:]

       self.prog_name = os.path.basename(self.argv[0])

       self.settings_exception = None

   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]#获取第二个参数,比如mange.py startapp,那就是startapp

      except IndexError:

      subcommand = 'help' # Display help if no arguments were given.

os.environ.setdefault:任何一个djangoproject中的*.py文件都能够正常的使用项目中的数据模型操作
__name__:如果通过manage.py本身调用,那么print(name)输出可以看到等于main
Python中的namemain含义详解

你可能感兴趣的:(Django源码解读[1])