Django 3.0 est officiellement sorti il y a 3 jours. Relâchez le lien du nœud Avec autant de changements, je suis très intéressé par l'ajout de la prise en charge de ʻASGI`, J'aimerais vraiment l'utiliser. : ensoleillé:
ASGI (Asynchronous Server Gateway Interface) est le successeur spirituel de WSGI et vise à fournir une interface standard entre les serveurs Web Python asynchrones, les frameworks et les applications.
Alors que WSGI fournissait la norme pour les applications Python synchrones, ASGI fournit à la fois des applications asynchrones et synchrones avec une implémentation de compatibilité descendante de WSGI et de plusieurs serveurs et cadres d'application.
Créer un environnement virtuel pour les tests
mkvirtualenv django3.0
Installez Django
pip3 install django
Une fois l'installation terminée, assurez-vous que vous disposez de Django 3.0
(django3.0) ~ $ pip3 list
Package Version
---------- -------
asgiref 3.2.3
Django 3.0
pip 19.3.1
pytz 2019.3
setuptools 42.0.2
sqlparse 0.3.0
wheel 0.33.6
Créons un nouveau projet et démarrons un serveur
mkdir django-test
&&
django-admin startproject newtest
&&
cd newtest/
&&
python3 manage.py runserver
Accédons au n ° 8000 et vous pourrez voir la fusée familière.
Jusqu'ici Yoshi!: Détendu :: point_up:
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)
python manage.py runserver
, il démarrera le serveur wsgi habituel.
--Il est recommandé d'utiliser Daphne
ou ʻUvicorn` lors du démarrage du serveur.Ouvrons le lien officiel pour voir ce qu'est «Daphne» lien
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.
Traduit --Installez daphné avec pip --Exécuter daphne myproject.asgi: application pour démarrer le serveur ASGI --Accès à 127.0.0.1.8000
Essayons: point_up:
installation de daphné
pip3 install daphne
Démarrage du serveur
daphne [Nom du projet].asgi:application
Quand j'ai accédé à 8000, j'ai pu revoir la fusée, même si les personnages ont un peu changé. : œil:
Je vais ouvrir un navigateur et envoyer un message Websocket.
«500» est renvoyé, le message d'erreur est le suivant.
2019-12-05 11:02:09,533 ERROR Exception inside application: Django can only handle ASGI/HTTP connections, not websocket.
File "/Envs/django3.0/lib/python3.7/site-packages/daphne/cli.py", line 30, in asgi
await self.app(scope, receive, send)
File "/Envs/django3.0/lib/python3.7/site-packages/django/core/handlers/asgi.py", line 146, in __call__
% scope['type']
Django can only handle ASGI/HTTP connections, not websocket.
Il semble y avoir quelque chose à la ligne 146 de ʻasgi.py`, jetons un œil.
asgi.py
async def __call__(self, scope, receive, send):
"""
Async entrypoint - parses the request and hands off to get_response.
"""
# 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']
)
# Receive the HTTP request body as a stream object.
try:
body_file = await self.read_body(receive)
except RequestAborted:
return
# Request is complete and can be served.
set_script_prefix(self.get_script_prefix(scope))
Notez le commentaire de deux lignes ci-dessous.
# Serve only HTTP connections.
# FIXME: Allow to override this.
Les causes possibles sont les suivantes.
Django 3.0 actuel, si vous souhaitez utiliser websocket, nous vous recommandons d'utiliser le package django-channel
.