当前位置 主页 > 服务器问题 > Linux/apache问题 >
此前博主曾经写过一篇博文,介绍了Django3.0的新特性,其中最主要的就是加入对ASGI的支持,实现全双工的异步通信。
2019年12月2日,Django终于正式发布了3.0版本。怀着无比的期待,我们来尝试一下吧!
(附ASGI官方文档地址:https://asgi.readthedocs.io/en/latest/extensions.html)
一、创建Django3工程
利用Pycharm的方便,直接通过virtualenv创建虚拟环境,并安装Django3.0。
打开控制台,看看都安装了哪些库:
(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,又自动安装了asgiref。
asigref由Django软件基金会开发和维护,是一个Django生态中的库。
先启动一下服务器,看看Django是否正常运行:
没毛病,可以把服务器关了!
二、学习官方文档
毕竟是非常重要和复杂的新特性,先到官网取取经,看看文档怎么写的。
找了一圈,What?就这么点东西?
先康康吧。
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)