[PYTHON] To celebrate the release of Django 3.0, I tried ASGI, the spiritual successor to WSGI, but I couldn't use websocket.

Celebration! Django 3.0 released!

02/02/2019 Django 3.0 has been released. Django 1.0 was released in 2008 and 2.0 was released in December 2017. And 3.0 was released on December 2nd of this year. It took about 10 years to upgrade from 1 to 2, but it was a surprising speed of less than 2 years from 2 to 3. What on earth have I been doing in the last two years compared to that? Now let's take a look at the new features that I personally care about in Django 3.0!

What is ASGI support?

I was curious about this. That said, I've never touched ASGI and officially supported it! Even though I was told, it was like that. But I have WSGI-san ... However, when I looked it up, it seemed that ASGI seemed to be something that couldn't be ignored.

According to the Release Notes, asynchronous functionality is currently not in WSGI and is only supported when run in ASGI. (But do you think we will support it in the future?). According to ASGI Official, "ASGI is WSGI's spiritual successor (spiritual sequel. wiki /% E7% B2% BE% E7% A5% 9E% E7% 9A% 84% E7% B6% 9A% E7% B7% A8)) ”. In this way, WSGI, which seemed to be my strong ally, seems to be backward compatible with ASGI.

It doesn't matter, but the word "spiritual sequel" is cool. It seems that Xenosaga for Xenogears, Perfect Dark for GoldenEye 007, etc. correspond to it. However, WSGI and ASGI are not games or fiction works, and are sequels really suitable? I thought, so I will read it as a spiritual successor. I wrote that in the title.

Try running Django with ASGI

If so, the story is quick, so I tried running Django with ASGI. Create an environment with Docker.

sudo docker run --rm -it -p 8000:8000 python:3.8 bash

I use python3.8. By the way, Django 3.0 supports python 3.6, 3.7, and 3.8.

pip install django daphne

Install daphne along with django. daphne looks like a server for ʻASGI. ʻU WSGI in WSGI is probably daphne in ʻASGI`. surely. By the way, daphne seems to be called daphne. django is django, but daphne's d should be pronounced properly.

django-admin startproject app
cd app
daphne -b 0.0.0.0 -p 8000 app.asgi:application

After installing, create a project and try running it immediately.

Hooray! moved! Finished!

django3.png

It worked, but I don't know what makes me happy. Well, of course. Even though the asynchronous function is for sale, it only communicates synchronously.

Isn't there a tutorial like building a chat app that allows you to try asynchronous communication with Django?

was. https://channels.readthedocs.io/en/latest/tutorial/index.html It seems that Django channels can use web sockets with Djang, and there is a polite chat app tutorial. It is my soul to try running a chat application made by copying this with daphne. However, I'm not sure about the relationship between Django channels and this ASGI support. Well, but don't go too deep as you may find out as you use it.

I will put the finished product made according to the tutorial here here. I will try to move it. It is in the state of command: python manage.py runserver 0.0.0.0:8000.

sudo docker-compose up -d

I confirmed the operation with 2 windows, but you can use chat properly.

mov2.gif

Now, let's move this with daphne. Rewrite command as follows:

 services:
     app:
         build: .
-        command: python manage.py runserver 0.0.0.0:8000
+        command: daphne -b 0.0.0.0 -p 8000 mysite.asgi:application
         volumes:
             - .:/srv
         ports:

This should work as I expected ...

sudo docker-compose down
sudo docker-compose up -d

ws.png Hmm, it doesn't work.

When I read the error message, it says that websocket cannot be used.

172.17.0.1:52480 - - [06/Dec/2019:07:36:28] "GET /chat/a/" 200 1413
172.17.0.1:52488 - - [06/Dec/2019:07:36:28] "WSCONNECTING /ws/chat/a/" - -
2019-12-06 07:36:29,471 ERROR    Exception inside application: Django can only handle ASGI/HTTP connections, not websocket.
  File "/usr/local/lib/python3.8/site-packages/daphne/cli.py", line 30, in asgi
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.8/site-packages/django/core/handlers/asgi.py", line 144, in __call__
    raise ValueError(
  Django can only handle ASGI/HTTP connections, not websocket.
172.17.0.1:52488 - - [06/Dec/2019:07:36:29] "WSDISCONNECT /ws/chat/a/" - -

Let's take a look around line 144 of 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']
            )

It seems that it throws an exception when it is not HTTP connections. What the hell is this?

I think it's either, but I'm not sure. The mystery is only deepening. However, it is officially stated that ASGI can support Django asynchronously, so I will continue to pay close attention to it.

end

Goodbye WSGI. I have ASGI ...

Recommended Posts

To celebrate the release of Django 3.0, I tried ASGI, the spiritual successor to WSGI, but I couldn't use websocket.
I tried the asynchronous server of Django 3.0
I tried to touch the API of ebay
I tried to correct the keystone of the image
I tried to predict the price of ETF
I tried to vectorize the lyrics of Hinatazaka46!
I tried to summarize the settings for various databases of Django (MySQL, PostgreSQL)
I tried to use Resultoon on Mac + AVT-C875, but I was frustrated on the way.
I tried to summarize how to use matplotlib of python
I tried to scrape YouTube, but I can use the API, so don't do it.
I want to scroll the Django shift table, but ...
I tried to summarize the basic form of GPLVM
I tried to erase the negative part of Meros
I tried to classify the voices of voice actors
I tried to summarize the string operations of Python
I tried to find the entropy of the image with python
[Horse Racing] I tried to quantify the strength of racehorses
I tried to get the location information of Odakyu Bus
I want to use only the normalization process of SudachiPy
[Python] I tried to visualize the follow relationship of Twitter
[Machine learning] I tried to summarize the theory of Adaboost
I tried to fight the Local Minimum of Goldstein-Price Function
I tried to summarize how to use the EPEL repository again
I tried to describe the traffic in real time with WebSocket
[Linux] I tried to summarize the command of resource confirmation system
I tried to get the index of the list using the enumerate function
I tried to automate the watering of the planter with Raspberry Pi
I tried to build the SD boot image of LicheePi Nano
I tried to summarize the frequently used implementation method of pytest-mock
I tried to improve the efficiency of daily work with Python
I compared while reading the documentation to use Jinja2 with Django
I tried to visualize the common condition of VTuber channel viewers
A super introduction to Django by Python beginners! Part 2 I tried using the convenient functions of the template
I want to use complicated four arithmetic operations in the IF statement of the Django template! → Use a custom template
I tried to move the ball
I tried to estimate the interval.
I tried to transform the face image using sparse_image_warp of TensorFlow Addons
I tried to get the batting results of Hachinai using image processing
I tried transcribing the news of the example business integration to Amazon Transcribe
I tried to estimate the similarity of the question intent using gensim's Doc2Vec
I tried how to improve the accuracy of my own Neural Network
I tried to solve the 2020 version of 100 language processing [Chapter 3: Regular expressions 25-29]
I want to use the Django Debug Toolbar in my Ajax application
I tried to automatically extract the movements of PES players with software
I tried to summarize the logical way of thinking about object orientation.
I tried to find the optimal path of the dreamland by (quantum) annealing
I tried to extract and illustrate the stage of the story using COTOHA
I tried to analyze the negativeness of Nono Morikubo. [Compare with Posipa]
I tried to streamline the standard role of new employees with Python
I tried to get the RSS of the top song of the iTunes store automatically
I tried to get the movie information of TMDb API with Python
I tried to display the altitude value of DTM in a graph
I tried the common story of using Deep Learning to predict the Nikkei 225
Using COTOHA, I tried to follow the emotional course of Run, Melos!
I tried to verify the result of A / B test by chi-square test
I tried to predict the behavior of the new coronavirus with the SEIR model.
I wanted to use the find module of Ansible2, but it took some time, so make a note
The tree.plot_tree of scikit-learn was very easy and convenient, so I tried to summarize how to use it easily.
I tried to summarize the umask command
How to check the version of Django
I tried to recognize the wake word