{"id":1234,"date":"2021-02-08T20:49:54","date_gmt":"2021-02-08T17:49:54","guid":{"rendered":"https:\/\/www.etemkeskin.com\/?p=1234"},"modified":"2021-02-08T20:50:16","modified_gmt":"2021-02-08T17:50:16","slug":"real-time-application-development-using-websocket-in-django","status":"publish","type":"post","link":"https:\/\/www.etemkeskin.com\/index.php\/2021\/02\/08\/real-time-application-development-using-websocket-in-django\/","title":{"rendered":"Real-Time Application Development Using Websocket in Django"},"content":{"rendered":"\n<p><strong>WebSocket<\/strong> is a computer communication protocol that provides a full duplex communication channel over a single TCP connection. All internet browsers have supported Websockets since 2011.<\/p>\n\n\n\n<p>Application development with Websocket is a popular topic. However, when developing a web application, it must be decided whether it is necessary to develop with websocket. <\/p>\n\n\n\n<h4>Which Web Applications can be Developed using Websocket <\/h4>\n\n\n\n<ol><li>Chat Apps<\/li><li>Real-time push nitifications<\/li><li>Real-time graph<\/li><li>Real-time applications (GPS tracking, reading instant data from sensors and taking action) by connecting with IOT devices (such as rasberrypie &#8230;)<\/li><li>Chat bots<\/li><\/ol>\n\n\n\n<p><strong>Django channels:<\/strong> It is a package that provides long-running connections for Django projects such as WebSockets, MQTT, chatbots, amateur radio and more &#8230; . It adds extra features to asynchronous views that come with Django.<\/p>\n\n\n\n<h4>Objectives<\/h4>\n\n\n\n<p>In this post<\/p>\n\n\n\n<ol><li>Providing Web sockets support to Django project using Django channels<\/li><li>Creating a publisher in Jupyter notebook and sending data to Django application with websockets.<\/li><li>By making a websocket connection in Frontend, we will update the data instantly.<\/li><\/ol>\n\n\n\n<p><strong>Libraries Needed<\/strong><\/p>\n\n\n\n<p>For our real-time application, we need to install the following libraries on our computer.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>pip install Django<\/code>\n<code>pip install -U channels<\/code>\n<code>pip&nbsp;install&nbsp;websocket-client<\/code>\n\n<strong>settings.py<\/strong><\/pre>\n\n\n\n<p>We need to define channels below INSTALLED_APPS in our settings.py file as follows. In our project, we started the application called<strong> liveapp<\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;showPanel&quot;:false,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">INSTALLED_APPS = [\n    'channels', # for async app  it must be top place\n  \n  \t'liveapp'<\/pre><\/div>\n\n\n\n<p>Since our application will work asynchronously, we need to define it as follows. In <strong>learndj<\/strong> project, we created a file named <strong>routing.py<\/strong> where we will define <strong>urls<\/strong>.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;showPanel&quot;:false,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">WSGI_APPLICATION = 'learndj.wsgi.application'\nASGI_APPLICATION = 'learndj.routing.application'<\/pre><\/div>\n\n\n\n<p>If we are going to use <strong>CHANNEL_LAYERS<\/strong> that came with Django, we add the following codes. If Redis will be used in real time application, you can use the commented part in the following codes.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;showPanel&quot;:false,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">CHANNEL_LAYERS = {\n    &quot;default&quot;: {\n        &quot;BACKEND&quot;: &quot;channels.layers.InMemoryChannelLayer&quot;\n    },\n}\n\n# CHANNEL_LAYERS = {\n#     &quot;default&quot;: {\n#         &quot;BACKEND&quot;: &quot;channels_redis.core.RedisChannelLayer&quot;,\n#         &quot;CONFIG&quot;: {\n#             &quot;hosts&quot;: [(&quot;localhost&quot;, 6379)],\n#         },\n#     },\n# }<\/pre><\/div>\n\n\n\n<p>The file structure of our <strong>learndj<\/strong> project is as follows.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"157\" height=\"218\" src=\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/02\/image-5.png\" alt=\"\" class=\"wp-image-1180\"\/><\/figure>\n\n\n\n<p><strong>routing.py<\/strong><\/p>\n\n\n\n<p>After creating the routing.py file, we will use the following codes. When defining the <strong>websocket url<\/strong>, we add <strong>ws\/<\/strong> prefix to separate it from other urls. <br>Consumer class that will run when a request is made to the websocket url is the <strong>DashConsumer<\/strong> class in the <strong>consumer.py<\/strong> file we created.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;showPanel&quot;:false,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">from channels.routing import ProtocolTypeRouter, URLRouter\nfrom channels.auth import AuthMiddlewareStack\nfrom django.urls import path\nfrom liveapp import consumer\n\nwebsocket_urlPattern = [\n    #In routing.py, &quot;as_asgi()&quot; is required for versions over python 3.6.\n    path('ws\/pollData', consumer.DashConsumer.as_asgi()), # add ws for prefix.\n]\n\napplication = ProtocolTypeRouter({\n    'websocket':AuthMiddlewareStack(URLRouter(websocket_urlPattern ))\n})<\/pre><\/div>\n\n\n\n<p><strong>consumer.py<\/strong><\/p>\n\n\n\n<p>Consumers are the equivalent of view functions in Django. We created our file named <strong>consumer.py<\/strong> in <strong>liveapp<\/strong> application.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"160\" height=\"226\" src=\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/02\/image-3.png\" alt=\"\" class=\"wp-image-1176\"\/><\/figure>\n\n\n\n<p>We have defined consumer functions that will work with the code block below. A user connecting to the websocket url of our application will be added to the <strong>dashboard<\/strong> group.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;showPanel&quot;:false,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">from channels.generic.websocket import AsyncJsonWebsocketConsumer\nimport json\n\nclass DashConsumer(AsyncJsonWebsocketConsumer):\n    print('==================')\n    async def connect(self):\n        self.groupname='dashboard'\n        await self.channel_layer.group_add(\n            self.groupname,\n            self.channel_name,\n        )\n        await self.accept()\n\n    async def disconnect(self,close_code):\n        await self.channel_layer.group_discard(\n            self.groupname,\n            self.channel_name\n        )   \n\n    async def receive(self, text_data):\n        datapoint = json.loads(text_data)\n        val =datapoint['value']\n\n        await self.channel_layer.group_send(\n            self.groupname,\n            {\n                'type':'deprocessing', #function name to run\n                'value':val #value to send function\n            }\n        )\n        print ('&gt;&gt;&gt;&gt;',text_data)\n\n    async def deprocessing(self,event):\n        valOther=event['value']\n        valOther = f'IP VALUE: {valOther}'\n        await self.send(text_data=json.dumps({'value2':valOther}))# send for frontend<\/pre><\/div>\n\n\n\n<p>The python script that will connect to our application and send data in json format is as follows. Data generated instantly in Jupyter notebook will be rendered in template.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"487\" height=\"352\" src=\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/02\/image-8.png\" alt=\"\" class=\"wp-image-1201\"\/><\/figure>\n\n\n\n<p>When we run Jupyter notebook, we print the incoming data in the receive function in consumer.py. We can see the printed json data in the command line where we run django as in the picture below.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"926\" height=\"441\" src=\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/02\/image-7.png\" alt=\"\" class=\"wp-image-1200\"\/><\/figure>\n\n\n\n<p>We create a template named <strong>live_app.html<\/strong> and add the following code block inside.<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;htmlmixed&quot;,&quot;mime&quot;:&quot;text\/html&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;showPanel&quot;:false,&quot;language&quot;:&quot;HTML&quot;,&quot;modeName&quot;:&quot;html&quot;}\">&lt;h2&gt;Live APP&lt;\/h2&gt;\n&lt;h3 id='poll_data'&gt;Data&lt;\/h3&gt;\n&lt;script&gt;\n  \tconst myDiv = document.getElementById('poll_data')\n    \n    let socket = new WebSocket('ws:\/\/localhost:8000\/ws\/pollData');\n    socket.onopen = function(e){\n        alert('connection established');\n    }\n\n    socket.onmessage = function(e){\n        console.log(e.data);\n        result = JSON.parse(e.data);\n      \tmyDiv.textContent = result.value2;\n    }\n\n    socket.onclose = function(e){\n        alert('connection closed');\n    }\n&lt;\/script&gt;<\/pre><\/div>\n\n\n\n<p>When we define any <strong>url<\/strong> and <strong>view<\/strong> that will render this template, we can see that the data is updated instantly as in the picture below.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" width=\"675\" height=\"258\" src=\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/02\/image-9.png\" alt=\"\" class=\"wp-image-1206\"\/><\/figure>\n\n\n\n<p>Good Luck &#8230;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>WebSocket is a computer communication protocol that provides a full duplex communication channel over a single TCP connection. All internet browsers have supported Websockets since 2011. Application development with Websocket is a popular topic. However, when developing a web application, it must be decided whether it is necessary to develop with websocket. Which Web Applications [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[30,4],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v16.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Real-Time Application Development Using Websocket in Django - blog website<\/title>\n<meta name=\"description\" content=\"WebSocket is a computer communication protocol that provides a full duplex communication channel over a single TCP connection. All internet browsers have supported Websockets since 2011. Application development with Websocket is a popular topic. However, when developing a web application, it must be decided whether it is necessary to develop with websocket.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.etemkeskin.com\/index.php\/2021\/02\/08\/real-time-application-development-using-websocket-in-django\/\" \/>\n<meta property=\"og:locale\" content=\"tr_TR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Real-Time Application Development Using Websocket in Django - blog website\" \/>\n<meta property=\"og:description\" content=\"WebSocket is a computer communication protocol that provides a full duplex communication channel over a single TCP connection. All internet browsers have supported Websockets since 2011. Application development with Websocket is a popular topic. However, when developing a web application, it must be decided whether it is necessary to develop with websocket.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.etemkeskin.com\/index.php\/2021\/02\/08\/real-time-application-development-using-websocket-in-django\/\" \/>\n<meta property=\"og:site_name\" content=\"blog website\" \/>\n<meta property=\"article:published_time\" content=\"2021-02-08T17:49:54+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-02-08T17:50:16+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/02\/image-5.png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Tahmini okuma s\u00fcresi\" \/>\n\t<meta name=\"twitter:data1\" content=\"4 dakika\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.etemkeskin.com\/#website\",\"url\":\"https:\/\/www.etemkeskin.com\/\",\"name\":\"blog website\",\"description\":\"Etem KESK\\u0130N\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/www.etemkeskin.com\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"tr\"},{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/02\/08\/real-time-application-development-using-websocket-in-django\/#primaryimage\",\"inLanguage\":\"tr\",\"url\":\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/02\/image-5.png\",\"contentUrl\":\"https:\/\/www.etemkeskin.com\/wp-content\/uploads\/2021\/02\/image-5.png\",\"width\":157,\"height\":218},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/02\/08\/real-time-application-development-using-websocket-in-django\/#webpage\",\"url\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/02\/08\/real-time-application-development-using-websocket-in-django\/\",\"name\":\"Real-Time Application Development Using Websocket in Django - blog website\",\"isPartOf\":{\"@id\":\"https:\/\/www.etemkeskin.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/02\/08\/real-time-application-development-using-websocket-in-django\/#primaryimage\"},\"datePublished\":\"2021-02-08T17:49:54+00:00\",\"dateModified\":\"2021-02-08T17:50:16+00:00\",\"author\":{\"@id\":\"https:\/\/www.etemkeskin.com\/#\/schema\/person\/dcbc30282861ce578b96a79ce8789629\"},\"description\":\"WebSocket is a computer communication protocol that provides a full duplex communication channel over a single TCP connection. All internet browsers have supported Websockets since 2011. Application development with Websocket is a popular topic. However, when developing a web application, it must be decided whether it is necessary to develop with websocket.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/02\/08\/real-time-application-development-using-websocket-in-django\/#breadcrumb\"},\"inLanguage\":\"tr\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.etemkeskin.com\/index.php\/2021\/02\/08\/real-time-application-development-using-websocket-in-django\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.etemkeskin.com\/index.php\/2021\/02\/08\/real-time-application-development-using-websocket-in-django\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Ana sayfa\",\"item\":\"https:\/\/www.etemkeskin.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Real-Time Application Development Using Websocket in Django\"}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.etemkeskin.com\/#\/schema\/person\/dcbc30282861ce578b96a79ce8789629\",\"name\":\"etemkeskin\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/www.etemkeskin.com\/#personlogo\",\"inLanguage\":\"tr\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/6af0148b790691ed24ae245fb3dc773b?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/6af0148b790691ed24ae245fb3dc773b?s=96&d=mm&r=g\",\"caption\":\"etemkeskin\"},\"url\":\"https:\/\/www.etemkeskin.com\/index.php\/author\/etemkeskinyahoo-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","_links":{"self":[{"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/posts\/1234"}],"collection":[{"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/comments?post=1234"}],"version-history":[{"count":27,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/posts\/1234\/revisions"}],"predecessor-version":[{"id":1263,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/posts\/1234\/revisions\/1263"}],"wp:attachment":[{"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/media?parent=1234"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/categories?post=1234"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.etemkeskin.com\/index.php\/wp-json\/wp\/v2\/tags?post=1234"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}