您好,登錄后才能下訂單哦!
Django3.0 中怎么實(shí)現(xiàn)異步通信,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
一、創(chuàng)建Django3工程
利用Pycharm的方便,直接通過virtualenv創(chuàng)建虛擬環(huán)境,并安裝Django3.0。
打開控制臺(tái),看看都安裝了哪些庫:
(venv) D:\work\for_test\django3>pip list Package Version ------ asgiref 3.2.3 Django 3.0 pip 10.0.1 pytz 2019.3 setuptools 39.1.0 sqlparse 0.3.0
除了pytz和sqlparse,又自動(dòng)安裝了asgiref。
asigref由Django軟件基金會(huì)開發(fā)和維護(hù),是一個(gè)Django生態(tài)中的庫。
先啟動(dòng)一下服務(wù)器,看看Django是否正常運(yùn)行:
沒毛病,可以把服務(wù)器關(guān)了!
二、學(xué)習(xí)官方文檔
畢竟是非常重要和復(fù)雜的新特性,先到官網(wǎng)取取經(jīng),看看文檔怎么寫的。
找了一圈,What?就這么點(diǎn)東西?
先康康吧。
How to deploy with ASGI As well as WSGI, Django also supports deploying on ASGI, the emerging Python standard for asynchronous web servers and applications. Django's startproject management command sets up a default ASGI configuration for you, which you can tweak as needed for your project, and direct any ASGI-compliant application server to use. Django includes getting-started documentation for the following ASGI servers: How to use Django with Daphne How to use Django with Uvicorn The application object Like WSGI, ASGI has you supply an application callable which the application server uses to communicate with your code. It's commonly provided as an object named application in a Python module accessible to the server. The startproject command creates a file <project_name>/asgi.py that contains such an application callable. It's not used by the development server (runserver), but can be used by any ASGI server either in development or in production. ASGI servers usually take the path to the application callable as a string; for most Django projects, this will look like myproject.asgi:application. Warning While Django's default ASGI handler will run all your code in a synchronous thread, if you choose to run your own async handler you must be aware of async-safety. Do not call blocking synchronous functions or libraries in any async code. Django prevents you from doing this with the parts of Django that are not async-safe, but the same may not be true of third-party apps or Python libraries. Configuring the settings module When the ASGI server loads your application, Django needs to import the settings module — that's where your entire application is defined. Django uses the DJANGO_SETTINGS_MODULE environment variable to locate the appropriate settings module. It must contain the dotted path to the settings module. You can use a different value for development and production; it all depends on how you organize your settings. If this variable isn't set, the default asgi.py sets it to mysite.settings, where mysite is the name of your project. Applying ASGI middleware To apply ASGI middleware, or to embed Django in another ASGI application, you can wrap Django's application object in the asgi.py file. For example: from some_asgi_library import AmazingMiddleware application = AmazingMiddleware(application)
文檔短小無力,內(nèi)容稀少!
總結(jié)就以下幾點(diǎn):
不能用python manage.py runserver的方式啟動(dòng)ASGI服務(wù)器,這只會(huì)啟動(dòng)傳統(tǒng)的、默認(rèn)的WSGI服務(wù)器,也就是老版本的東西
要啟動(dòng)ASGI服務(wù)器,你需要使用Daphne或者Uvicorn。推薦使用Daphne,這是Django軟件基金會(huì)開發(fā)的一個(gè)基于ASGI (HTTP/WebSocket)的服務(wù)器。
有一個(gè)myproject.asgi:application文件,是ASGI通信的接口,Django默認(rèn)自帶
你可以配置DJANGO_SETTINGS_MODULE 環(huán)境,或者使用默認(rèn)的your_project.settings
可以使用第三方ASGI中間件
再簡(jiǎn)單粗暴點(diǎn),全文的意思是,你需要安裝Daphne,然后調(diào)用Django的application來啟動(dòng)ASGI服務(wù)器。
好吧,我們看看Daphne,點(diǎn)擊Django給的連接,跳轉(zhuǎn)到相關(guān)頁面,內(nèi)容更少:
How to use Django with Daphne Daphne is a pure-Python ASGI server for UNIX, maintained by members of the Django project. It acts as the reference server for ASGI. Installing Daphne You can install Daphne with pip: python -m pip install daphne Running Django in Daphne When Daphne is installed, a daphne command is available which starts the Daphne server process. At its simplest, Daphne needs to be called with the location of a module containing an ASGI application object, followed by what the application is called (separated by a colon). For a typical Django project, invoking Daphne would look like: daphne myproject.asgi:application This will start one process listening on 127.0.0.1:8000. It requires that your project be on the Python path; to ensure that run this command from the same directory as your manage.py file.
翻譯過來就是:
pip安裝daphne
執(zhí)行daphne myproject.asgi:application命令,啟動(dòng)ASGI服務(wù)器
瀏覽器訪問127.0.0.1:8000
咱們照做!
三、啟動(dòng)ASGI服務(wù)器
通過pip install daphne
即可安裝最新版本的daphne:
Collecting pycparser (from cffi!=1.11.3,>=1.8->cryptography>=2.7->autobahn>=0.18->daphne) Installing collected packages: idna, hyperlink, zope.interface, attrs, six, Automat, constantly, PyHamcrest, incremental, pycparser, cffi, cry ptography, pyopenssl, pyasn1, pyasn1-modules, service-identity, twisted, txaio, autobahn, daphne Successfully installed Automat-0.8.0 PyHamcrest-1.9.0 attrs-19.3.0 autobahn-19.11.1 cffi-1.13.2 constantly-15.1.0 cryptography-2.8 daphne-2.4. 0 hyperlink-19.0.0 idna-2.8 incremental-17.5.0 pyasn1-0.4.8 pyasn1-modules-0.2.7 pycparser-2.19 pyopenssl-19.1.0 service-identity-18.1.0 six-1 .13.0 twisted-19.10.0 txaio-18.8.1 zope.interface-4.7.1
為了安裝daphne,需要額外安裝這么多依賴包!我們?cè)賞ip list看一下:
(venv) D:\work\for_test\django3>pip list Package Version ---------------- ------- asgiref 3.2.3 attrs 19.3.0 autobahn 19.11.1 Automat 0.8.0 cffi 1.13.2 constantly 15.1.0 cryptography 2.8 daphne 2.4.0 Django 3.0 hyperlink 19.0.0 idna 2.8 incremental 17.5.0 pip 10.0.1 pyasn1 0.4.8 pyasn1-modules 0.2.7 pycparser 2.19 PyHamcrest 1.9.0 pyOpenSSL 19.1.0 pytz 2019.3 service-identity 18.1.0 setuptools 39.1.0 six 1.13.0 sqlparse 0.3.0 Twisted 19.10.0 txaio 18.8.1 zope.interface 4.7.1
不管了,就當(dāng)沒看見。
安裝成功后,我們會(huì)獲得一個(gè)daphne可執(zhí)行命令,下面我們來啟動(dòng)服務(wù)器吧。
執(zhí)行daphne django3.asgi:application
命令。(將其中的django3換成你的工程名字,在manage.py文件所在的路徑下執(zhí)行)
(venv) D:\work\for_test\django3>daphne django3.asgi:application 2019-12-04 10:20:07,637 INFO Starting server at tcp:port=8000:interface=127.0.0.1 2019-12-04 10:20:07,637 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2019-12-04 10:20:07,637 INFO Configuring endpoint tcp:port=8000:interface=127.0.0.1 2019-12-04 10:20:07,637 INFO Listening on TCP address 127.0.0.1:8000
當(dāng)然,我們也是可以指定ip和port等參數(shù)的,詳細(xì)請(qǐng)學(xué)習(xí)daphne文檔https://pypi.org/project/daphne/
讀一下人家的啟動(dòng)信息:
默認(rèn)啟動(dòng)地址是127.0.0.1:8000
沒有開啟HTTP/2的支持(需要安裝額外的包)
配置了端點(diǎn),開始監(jiān)聽端口
Nice,通過瀏覽器來訪問一下吧!
依然是熟悉的白底火箭圖!圖片我就不貼了,看起來沒問題。
可是,這是基于HTTP的同步通信,還不是異步請(qǐng)求!讓我們嘗試一下websocket吧!
四、嘗試Websocket
瀏覽器中按F12進(jìn)入‘坦克模式',再進(jìn)入console控制臺(tái),嘗試發(fā)送一個(gè)Websocket請(qǐng)求:
忽視前面的css問題,重點(diǎn)在于這個(gè)ws請(qǐng)求,居然無法建立連接!返回狀態(tài)碼500,也就是服務(wù)器錯(cuò)誤!
再看看Pycharm后臺(tái)的信息:
127.0.0.1:5991 - - [04/Dec/2019:10:30:05] "WSCONNECTING /" - - 2019-12-04 10:30:05,246 ERROR Exception inside application: Django can only handle ASGI/HTTP connections, not websocket. File "d:\work\for_test\django3\venv\lib\site-packages\daphne\cli.py", line 30, in asgi await self.app(scope, receive, send) File "d:\work\for_test\django3\venv\lib\site-packages\django\core\handlers\asgi.py", line 146, in __call__ % scope['type'] Django can only handle ASGI/HTTP connections, not websocket. 127.0.0.1:5991 - - [04/Dec/2019:10:30:05] "WSDISCONNECT /" - -
重點(diǎn)在這句Django can only handle ASGI/HTTP connections, not websocket.
什么?Django不支持Websocket?說好的ASGI,說好的全雙工異步通信呢?
難道是我哪里搞錯(cuò)了?不行,我得看看源碼去!
五、Django3.0源碼
一路點(diǎn)點(diǎn)點(diǎn),翻了個(gè)遍,發(fā)現(xiàn)Django3.0與之前的2.2關(guān)于ASGI的區(qū)別就是多了下面兩個(gè)文件:
django.core.asgi
很簡(jiǎn)單,一看就懂,不多說:
import django from django.core.handlers.asgi import ASGIHandler def get_asgi_application(): django.setup(set_prefix=False) return ASGIHandler()
關(guān)鍵是django.core.handlers.asgi
這個(gè)文件,不到300行,總共就2個(gè)類,代碼就不貼了:
ASGIRequest:繼承了HttpRequest類,一看就知道是構(gòu)造請(qǐng)求對(duì)象
ASGIHandler:繼承了base.BaseHandler,這個(gè)就類似WSGIHandler,用于具體處理ASGI請(qǐng)求
讓我們看看它的其中一段代碼:
# Serve only HTTP connections. # FIXME: Allow to override this. if scope['type'] != 'http': raise ValueError( 'Django can only handle ASGI/HTTP connections, not %s.' % scope['type'] )
這就是我們前面在瀏覽器中發(fā)送ws請(qǐng)求,但是無法建立連接的原因!
如果scope的type屬性不是http,那么彈出ValueError異常,并提示不支持該類連接!
再看看人家寫的注釋,明明白白的寫著Serve only HTTP connections. FIXME: Allow to override this.
。翻譯過來就是只支持HTTP連接,請(qǐng)自己重寫這部分內(nèi)容修復(fù)這個(gè)缺陷。FIXME!FIXME!
好吧,我承認(rèn)白高興了一場(chǎng)。
六、總結(jié)
與Django3.0關(guān)于異步通信的初體驗(yàn)很不好,有下面幾點(diǎn)猜測(cè):
可能我水平不行,不會(huì)用Django
可能不是通過Websocket,而是別的手段與ASGI通信
Django真的目前只提供了個(gè)接口,內(nèi)部實(shí)現(xiàn)還沒做
由于相關(guān)資料太少,多方查找,據(jù)說:
Django會(huì)在后續(xù)的版本陸續(xù)實(shí)現(xiàn)完整的原生的異步通信能力,從同步機(jī)制切換到可兼容的異步機(jī)制
目前3.0階段,要與websocket通信依然得通過django-channel庫,還不是原生支持
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。