之前在網上看過一些介紹Django處理請求的流程和Django源碼結構的文章,覺得了解一下這些內容對開發Django項目還是很有幫助的。所以,我按照自己的邏輯總結了一下Django項目的運行方式和對Request的基本處理流程。
一、Django的運行方式
運行Django項目的方法很多,這里主要介紹一下常用的方法。一種是在開發和調試中經常用到runserver方法,使用Django自己的web server;另外一種就是使用fastcgi,uWSGIt等協議運行Django項目,這里以uWSGIt為例。
1、runserver方法
runserver方法是調試Django時經常用到的運行方式,它使用Django自帶的WSGI Server運行,主要在測試和開發中使用,使用方法如下:
Usage: manage.py runserver [options] [optional port number, or ipaddr:port]# python manager.py runserver # default port is 8000# python manager.py runserver 8080# python manager.py runserver 127.0.0.1:9090
看一下manager.py的源碼,你會發現上面的命令其實是通過Django的execute_from_command_line方法執行了內部實現的runserver命令,那么現在看一下runserver具體做了什么。。
看了源碼之后,可以發現runserver命令主要做了兩件事情:
1). 解析參數,并通過django.core.servers.basehttp.get_internal_wsgi_application方法獲取wsgi handler;
2). 根據ip_address和port生成一個WSGIServer對象,接受用戶請求
get_internal_wsgi_application的源碼如下:def get_internal_wsgi_application(): """ Loads and returns the WSGI application as configured by the user in ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout, this will be the ``application`` object in ``projectname/wsgi.py``. This function, and the ``WSGI_APPLICATION`` setting itself, are only useful for Django's internal servers (runserver, runfcgi); external WSGI servers should just be configured to point to the correct application object directly. If settings.WSGI_APPLICATION is not set (is ``None``), we just return whatever ``django.core.wsgi.get_wsgi_application`` returns. """ from django.conf import settings app_path = getattr(settings, 'WSGI_APPLICATION') if app_path is None: return get_wsgi_application() return import_by_path( app_path, error_prefix="WSGI application '%s' could not be loaded; " % app_path )
通過上面的代碼我們可以知道,Django會先根據settings中的WSGI_APPLICATION來獲取handler;在創建project的時候,Django會默認創建一個wsgi.py文件,而settings中的WSGI_APPLICATION配置也會默認指向這個文件。看一下這個wsgi.py文件,其實它也和上面的邏輯一樣,最終調用get_wsgi_application實現。
2、uWSGI方法
uWSGI+Nginx的方法是現在最常見的在生產環境中運行Django的方法,本人的博客也是使用這種方法運行,要了解這種方法,首先要了解一下WSGI和uWSGI協議。
新聞熱點
疑難解答