I believe to become a better developer you MUST get a better understanding of the underlying software systems you use on a daily basis and that includes programming languages, compilers and interpreters, databases and operating systems, web servers and web frameworks. And, to get a better and deeper understanding of those systems you MUST re-build them from scratch, brick by brick, wall by wall.python
筆者摘抄了一段話,送給閱讀本文的讀者web
如何分析django源碼,筆者選擇從django項目的啓動方式開始 python manage.py runserver,本文主要分析了django項目的啓動流程django
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "order.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)
在manage.py文件中,咱們看到啓動文件的入口是 excute_from_command_line(sys.argv)瀏覽器
def execute_from_command_line(argv=None): """ A simple method that runs a ManagementUtility. """ utility = ManagementUtility(argv) utility.execute()
這個函數是將命令行參數傳遞給了ManagementUtility類,這個類的execute方法負責執行,這個方法主要是一些django的初始化參數的檢查,以及經過sys.argv獲取命令,獲得相應的命令後,執行命令。服務器
execute方法中的部分代碼
... 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 ...
execute方法中有一段代碼autoreload.check_errors(django.setup)(),會對django項目進行一些必要的初始化,並檢查初始化的錯誤 django.setup()方法會註冊項目app和配置日誌文件,註冊app即對settings.INSTALLED_APPS中的app進行導入,並執行一些初始化方法app
進行完全部初始化動做,繼續執行代碼框架
execute方法中的部分代碼
... 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) ...
self.fetch_command(subcommand)會返回一個BaseCommand類,主要是分析subcommand參數(subcommand是sys.argv裏面獲取到的),導入相應的命令類,最後返回類socket
咱們經過分析,runserver參數最終獲取到的命令類是django/contrib/staticfiles/management/command/runserver.py 裏的Command類函數
這是Command類的繼承關係圖。Command類經過run_from_argv(self.argv)執行命令fetch
BaseCommand類中run_from_argv方法的部分代碼
... try: self.execute(*args, **cmd_options) except Exception as e: if options.traceback or not isinstance(e, CommandError): raise ...
run_from_argv(self.argv)方法中主要經過execute()來繼續執行,excute中會對django項目進行檢查,而後經過self.handle()繼續執行
RunserverCommand類裏面的handle方法部分代碼
def handle(self, *args, **options):
...
if not self.addr: self.addr = '::1' if self.use_ipv6 else '127.0.0.1' self._raw_ipv6 = self.use_ipv6 self.run(**options)
handle()方法裏面也進行了一些檢查,而後繼續執行self.run()來啓動服務器
RunserverCommand中的部分代碼 def run(self, **options): """ Runs the server, using the autoreloader if needed """ use_reloader = options['use_reloader'] if use_reloader: autoreload.main(self.inner_run, None, options) else: self.inner_run(None, **options) def inner_run(self, *args, **options): ... try: handler = self.get_handler(*args, **options) run(self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) except socket.error as e: ...
run方法中選擇了啓動的解釋器,最後都是經過inner_run中的run方法來執行,會啓動一個WSGIServer, WSGIServer須要一個回調函數handler(或者application),來執行django視圖裏面代碼。
至此,django項目服務器啓動流程完畢,啓動了一個簡單的WSGIServer,開始接受請求,解析請求參數,將請求參數傳遞給回調函數handler(或者application,django框架的核心內容),handler根據參數執行相應的代碼,返回數據給WSGIServer,WSGIServer最終將數據返回給瀏覽器。
關於wsgi能夠參考這篇文章,理解Python WSGI
我認爲django啓動流程中對於咱們開發者最重要的一步在於django.setup(),裏面作了不少初始化的工做,包括導入各個app的models,運行各個app的run函數,配置日誌文件。咱們若是想要在項目的啓動的時候作一些咱們本身的初始化動做,能夠選擇在這個地方下手。