Websocket disconnect with Channels in Django












1















I'm beginner with Django. I would like to use websockets with Channels. In this way I'm following this tutorial to create a simple chat.



I show you my files.



chat/consumers.py



from channels.generic.websocket import WebsocketConsumer
import json

class ChatConsumer(WebsocketConsumer):
def connect(self):
self.accept()

def disconnect(self, close_code):
pass

def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']

self.send(text_data=json.dumps({
'message': message
}))


My template file room.html :



<!-- chat/templates/chat/room.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<textarea id="chat-log" cols="100" rows="20"></textarea><br/>
<input id="chat-message-input" type="text" size="100"/><br/>
<input id="chat-message-submit" type="button" value="Send"/>
</body>
<script>
var roomName = {{ room_name_json }};

var chatSocket = new WebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/');

chatSocket.onmessage = function(e) {
var data = JSON.parse(e.data);
var message = data['message'];
document.querySelector('#chat-log').value += (message + 'n');
};

chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};

document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};

document.querySelector('#chat-message-submit').onclick = function(e) {
var messageInputDom = document.querySelector('#chat-message-input');
var message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));

messageInputDom.value = '';
};
</script>
</html>


Root routing configuration :



# mysite/routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing

application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})


And my routing.py file :



# chat/routing.py
from django.conf.urls import url

from . import consumers

websocket_urlpatterns = [
url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
]


When I run my ASGI server and I arrive on the page http://127.0.0.1:8000/chat/Test/, I'm getting the following message error :



HTTP GET /chat/Test/ 200 [0.00, 127.0.0.1:2807]
[Failure instance: Traceback: <class 'ValueError'>: No application configured for scope type 'websocket'
C:UserskevinEnvsmyprojectlibsite-packagesautobahnwebsocketprotocol.py:2801:processHandshake
C:UserskevinEnvsmyprojectlibsite-packagestxaiotx.py:429:as_future
C:UserskevinEnvsmyprojectlibsite-packagestwistedinternetdefer.py:151:maybeDeferred
C:UserskevinEnvsmyprojectlibsite-packagesdaphnews_protocol.py:82:onConnect
--- <exception caught here> ---
C:UserskevinEnvsmyprojectlibsite-packagestwistedinternetdefer.py:151:maybeDeferred
C:UserskevinEnvsmyprojectlibsite-packagesdaphneserver.py:198:create_application
C:UserskevinEnvsmyprojectlibsite-packageschannelsstaticfiles.py:41:__call__
C:UserskevinEnvsmyprojectlibsite-packageschannelsrouting.py:61:__call__
]
WebSocket DISCONNECT /ws/chat/Test/ [127.0.0.1:2814]


Would you have an idea of the problem ? :)



This question is similar, but no answer has been provided.



Thank you !



EDIT



I notice a strange thing, if I put wrong code in my file routing.py, the server doesn't notice it. It is like it doesn't read this file. For example if I turn the routing.py file like this :



# chat/routing.py
from django.conf.urls import url

from . import consumers

websocket_urlpatterns = [
url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),ezvzev
]


The server doesn't display any error message.










share|improve this question





























    1















    I'm beginner with Django. I would like to use websockets with Channels. In this way I'm following this tutorial to create a simple chat.



    I show you my files.



    chat/consumers.py



    from channels.generic.websocket import WebsocketConsumer
    import json

    class ChatConsumer(WebsocketConsumer):
    def connect(self):
    self.accept()

    def disconnect(self, close_code):
    pass

    def receive(self, text_data):
    text_data_json = json.loads(text_data)
    message = text_data_json['message']

    self.send(text_data=json.dumps({
    'message': message
    }))


    My template file room.html :



    <!-- chat/templates/chat/room.html -->
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8"/>
    <title>Chat Room</title>
    </head>
    <body>
    <textarea id="chat-log" cols="100" rows="20"></textarea><br/>
    <input id="chat-message-input" type="text" size="100"/><br/>
    <input id="chat-message-submit" type="button" value="Send"/>
    </body>
    <script>
    var roomName = {{ room_name_json }};

    var chatSocket = new WebSocket(
    'ws://' + window.location.host +
    '/ws/chat/' + roomName + '/');

    chatSocket.onmessage = function(e) {
    var data = JSON.parse(e.data);
    var message = data['message'];
    document.querySelector('#chat-log').value += (message + 'n');
    };

    chatSocket.onclose = function(e) {
    console.error('Chat socket closed unexpectedly');
    };

    document.querySelector('#chat-message-input').focus();
    document.querySelector('#chat-message-input').onkeyup = function(e) {
    if (e.keyCode === 13) { // enter, return
    document.querySelector('#chat-message-submit').click();
    }
    };

    document.querySelector('#chat-message-submit').onclick = function(e) {
    var messageInputDom = document.querySelector('#chat-message-input');
    var message = messageInputDom.value;
    chatSocket.send(JSON.stringify({
    'message': message
    }));

    messageInputDom.value = '';
    };
    </script>
    </html>


    Root routing configuration :



    # mysite/routing.py
    from channels.auth import AuthMiddlewareStack
    from channels.routing import ProtocolTypeRouter, URLRouter
    import chat.routing

    application = ProtocolTypeRouter({
    # (http->django views is added by default)
    'websocket': AuthMiddlewareStack(
    URLRouter(
    chat.routing.websocket_urlpatterns
    )
    ),
    })


    And my routing.py file :



    # chat/routing.py
    from django.conf.urls import url

    from . import consumers

    websocket_urlpatterns = [
    url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
    ]


    When I run my ASGI server and I arrive on the page http://127.0.0.1:8000/chat/Test/, I'm getting the following message error :



    HTTP GET /chat/Test/ 200 [0.00, 127.0.0.1:2807]
    [Failure instance: Traceback: <class 'ValueError'>: No application configured for scope type 'websocket'
    C:UserskevinEnvsmyprojectlibsite-packagesautobahnwebsocketprotocol.py:2801:processHandshake
    C:UserskevinEnvsmyprojectlibsite-packagestxaiotx.py:429:as_future
    C:UserskevinEnvsmyprojectlibsite-packagestwistedinternetdefer.py:151:maybeDeferred
    C:UserskevinEnvsmyprojectlibsite-packagesdaphnews_protocol.py:82:onConnect
    --- <exception caught here> ---
    C:UserskevinEnvsmyprojectlibsite-packagestwistedinternetdefer.py:151:maybeDeferred
    C:UserskevinEnvsmyprojectlibsite-packagesdaphneserver.py:198:create_application
    C:UserskevinEnvsmyprojectlibsite-packageschannelsstaticfiles.py:41:__call__
    C:UserskevinEnvsmyprojectlibsite-packageschannelsrouting.py:61:__call__
    ]
    WebSocket DISCONNECT /ws/chat/Test/ [127.0.0.1:2814]


    Would you have an idea of the problem ? :)



    This question is similar, but no answer has been provided.



    Thank you !



    EDIT



    I notice a strange thing, if I put wrong code in my file routing.py, the server doesn't notice it. It is like it doesn't read this file. For example if I turn the routing.py file like this :



    # chat/routing.py
    from django.conf.urls import url

    from . import consumers

    websocket_urlpatterns = [
    url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),ezvzev
    ]


    The server doesn't display any error message.










    share|improve this question



























      1












      1








      1








      I'm beginner with Django. I would like to use websockets with Channels. In this way I'm following this tutorial to create a simple chat.



      I show you my files.



      chat/consumers.py



      from channels.generic.websocket import WebsocketConsumer
      import json

      class ChatConsumer(WebsocketConsumer):
      def connect(self):
      self.accept()

      def disconnect(self, close_code):
      pass

      def receive(self, text_data):
      text_data_json = json.loads(text_data)
      message = text_data_json['message']

      self.send(text_data=json.dumps({
      'message': message
      }))


      My template file room.html :



      <!-- chat/templates/chat/room.html -->
      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="utf-8"/>
      <title>Chat Room</title>
      </head>
      <body>
      <textarea id="chat-log" cols="100" rows="20"></textarea><br/>
      <input id="chat-message-input" type="text" size="100"/><br/>
      <input id="chat-message-submit" type="button" value="Send"/>
      </body>
      <script>
      var roomName = {{ room_name_json }};

      var chatSocket = new WebSocket(
      'ws://' + window.location.host +
      '/ws/chat/' + roomName + '/');

      chatSocket.onmessage = function(e) {
      var data = JSON.parse(e.data);
      var message = data['message'];
      document.querySelector('#chat-log').value += (message + 'n');
      };

      chatSocket.onclose = function(e) {
      console.error('Chat socket closed unexpectedly');
      };

      document.querySelector('#chat-message-input').focus();
      document.querySelector('#chat-message-input').onkeyup = function(e) {
      if (e.keyCode === 13) { // enter, return
      document.querySelector('#chat-message-submit').click();
      }
      };

      document.querySelector('#chat-message-submit').onclick = function(e) {
      var messageInputDom = document.querySelector('#chat-message-input');
      var message = messageInputDom.value;
      chatSocket.send(JSON.stringify({
      'message': message
      }));

      messageInputDom.value = '';
      };
      </script>
      </html>


      Root routing configuration :



      # mysite/routing.py
      from channels.auth import AuthMiddlewareStack
      from channels.routing import ProtocolTypeRouter, URLRouter
      import chat.routing

      application = ProtocolTypeRouter({
      # (http->django views is added by default)
      'websocket': AuthMiddlewareStack(
      URLRouter(
      chat.routing.websocket_urlpatterns
      )
      ),
      })


      And my routing.py file :



      # chat/routing.py
      from django.conf.urls import url

      from . import consumers

      websocket_urlpatterns = [
      url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
      ]


      When I run my ASGI server and I arrive on the page http://127.0.0.1:8000/chat/Test/, I'm getting the following message error :



      HTTP GET /chat/Test/ 200 [0.00, 127.0.0.1:2807]
      [Failure instance: Traceback: <class 'ValueError'>: No application configured for scope type 'websocket'
      C:UserskevinEnvsmyprojectlibsite-packagesautobahnwebsocketprotocol.py:2801:processHandshake
      C:UserskevinEnvsmyprojectlibsite-packagestxaiotx.py:429:as_future
      C:UserskevinEnvsmyprojectlibsite-packagestwistedinternetdefer.py:151:maybeDeferred
      C:UserskevinEnvsmyprojectlibsite-packagesdaphnews_protocol.py:82:onConnect
      --- <exception caught here> ---
      C:UserskevinEnvsmyprojectlibsite-packagestwistedinternetdefer.py:151:maybeDeferred
      C:UserskevinEnvsmyprojectlibsite-packagesdaphneserver.py:198:create_application
      C:UserskevinEnvsmyprojectlibsite-packageschannelsstaticfiles.py:41:__call__
      C:UserskevinEnvsmyprojectlibsite-packageschannelsrouting.py:61:__call__
      ]
      WebSocket DISCONNECT /ws/chat/Test/ [127.0.0.1:2814]


      Would you have an idea of the problem ? :)



      This question is similar, but no answer has been provided.



      Thank you !



      EDIT



      I notice a strange thing, if I put wrong code in my file routing.py, the server doesn't notice it. It is like it doesn't read this file. For example if I turn the routing.py file like this :



      # chat/routing.py
      from django.conf.urls import url

      from . import consumers

      websocket_urlpatterns = [
      url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),ezvzev
      ]


      The server doesn't display any error message.










      share|improve this question
















      I'm beginner with Django. I would like to use websockets with Channels. In this way I'm following this tutorial to create a simple chat.



      I show you my files.



      chat/consumers.py



      from channels.generic.websocket import WebsocketConsumer
      import json

      class ChatConsumer(WebsocketConsumer):
      def connect(self):
      self.accept()

      def disconnect(self, close_code):
      pass

      def receive(self, text_data):
      text_data_json = json.loads(text_data)
      message = text_data_json['message']

      self.send(text_data=json.dumps({
      'message': message
      }))


      My template file room.html :



      <!-- chat/templates/chat/room.html -->
      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="utf-8"/>
      <title>Chat Room</title>
      </head>
      <body>
      <textarea id="chat-log" cols="100" rows="20"></textarea><br/>
      <input id="chat-message-input" type="text" size="100"/><br/>
      <input id="chat-message-submit" type="button" value="Send"/>
      </body>
      <script>
      var roomName = {{ room_name_json }};

      var chatSocket = new WebSocket(
      'ws://' + window.location.host +
      '/ws/chat/' + roomName + '/');

      chatSocket.onmessage = function(e) {
      var data = JSON.parse(e.data);
      var message = data['message'];
      document.querySelector('#chat-log').value += (message + 'n');
      };

      chatSocket.onclose = function(e) {
      console.error('Chat socket closed unexpectedly');
      };

      document.querySelector('#chat-message-input').focus();
      document.querySelector('#chat-message-input').onkeyup = function(e) {
      if (e.keyCode === 13) { // enter, return
      document.querySelector('#chat-message-submit').click();
      }
      };

      document.querySelector('#chat-message-submit').onclick = function(e) {
      var messageInputDom = document.querySelector('#chat-message-input');
      var message = messageInputDom.value;
      chatSocket.send(JSON.stringify({
      'message': message
      }));

      messageInputDom.value = '';
      };
      </script>
      </html>


      Root routing configuration :



      # mysite/routing.py
      from channels.auth import AuthMiddlewareStack
      from channels.routing import ProtocolTypeRouter, URLRouter
      import chat.routing

      application = ProtocolTypeRouter({
      # (http->django views is added by default)
      'websocket': AuthMiddlewareStack(
      URLRouter(
      chat.routing.websocket_urlpatterns
      )
      ),
      })


      And my routing.py file :



      # chat/routing.py
      from django.conf.urls import url

      from . import consumers

      websocket_urlpatterns = [
      url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
      ]


      When I run my ASGI server and I arrive on the page http://127.0.0.1:8000/chat/Test/, I'm getting the following message error :



      HTTP GET /chat/Test/ 200 [0.00, 127.0.0.1:2807]
      [Failure instance: Traceback: <class 'ValueError'>: No application configured for scope type 'websocket'
      C:UserskevinEnvsmyprojectlibsite-packagesautobahnwebsocketprotocol.py:2801:processHandshake
      C:UserskevinEnvsmyprojectlibsite-packagestxaiotx.py:429:as_future
      C:UserskevinEnvsmyprojectlibsite-packagestwistedinternetdefer.py:151:maybeDeferred
      C:UserskevinEnvsmyprojectlibsite-packagesdaphnews_protocol.py:82:onConnect
      --- <exception caught here> ---
      C:UserskevinEnvsmyprojectlibsite-packagestwistedinternetdefer.py:151:maybeDeferred
      C:UserskevinEnvsmyprojectlibsite-packagesdaphneserver.py:198:create_application
      C:UserskevinEnvsmyprojectlibsite-packageschannelsstaticfiles.py:41:__call__
      C:UserskevinEnvsmyprojectlibsite-packageschannelsrouting.py:61:__call__
      ]
      WebSocket DISCONNECT /ws/chat/Test/ [127.0.0.1:2814]


      Would you have an idea of the problem ? :)



      This question is similar, but no answer has been provided.



      Thank you !



      EDIT



      I notice a strange thing, if I put wrong code in my file routing.py, the server doesn't notice it. It is like it doesn't read this file. For example if I turn the routing.py file like this :



      # chat/routing.py
      from django.conf.urls import url

      from . import consumers

      websocket_urlpatterns = [
      url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),ezvzev
      ]


      The server doesn't display any error message.







      python django django-channels






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 1 at 21:18







      FrancNovation

















      asked Jan 1 at 19:51









      FrancNovationFrancNovation

      82112




      82112
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I have found my error ...
          I put the file routing.py inside of the first directory : sitetest
          Whereas I had to put it inside of sitetestsitetest






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53998469%2fwebsocket-disconnect-with-channels-in-django%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I have found my error ...
            I put the file routing.py inside of the first directory : sitetest
            Whereas I had to put it inside of sitetestsitetest






            share|improve this answer




























              0














              I have found my error ...
              I put the file routing.py inside of the first directory : sitetest
              Whereas I had to put it inside of sitetestsitetest






              share|improve this answer


























                0












                0








                0







                I have found my error ...
                I put the file routing.py inside of the first directory : sitetest
                Whereas I had to put it inside of sitetestsitetest






                share|improve this answer













                I have found my error ...
                I put the file routing.py inside of the first directory : sitetest
                Whereas I had to put it inside of sitetestsitetest







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 1 at 21:29









                FrancNovationFrancNovation

                82112




                82112
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53998469%2fwebsocket-disconnect-with-channels-in-django%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                    SQL update select statement

                    'app-layout' is not a known element: how to share Component with different Modules