Django Channels Tutorial 🔥: Real Time Graph with Chart.js | Django Websocket

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video i'll create this app it's a quite simple django django channels application that uses chart.js to create and update this graph values that are used by the chart.js library are generated by django and then they are sent via the websocket protocol to this page this time it's the asynchronous code that can handle several clients if i open the second tab and make a request to the page i'll get the same results so let's do it firstly i want to repeat my last jungle channels synchronous app and then i want to modify it to an asynchronous application and after that i will add to it the charge.js library first of all i have to create a basic django project with one app and one template i have to install janga now i want to create a django project let's say it will be real time graph project then i want to create an app let's say it'll be the graph app also let's apply migrations and let's start the djangos development server okay and now on the level of the manage py file i want to create two folders the templates folder and the static folder templates for hdmi templates and static folder to store javascript files so let's create in the static folder the main.js file and in the templates folder i want to create let's say the base html file also i want to use here bootstrap library bootstrap css just copy the link from the getbootstub.com website here i want to use the standard bootstrap layout here so i need the container block with the child raw with the child div with the 10 bootstrap columns width i want to have it centered and the margin from top and 5. okay then in the main.js let's console look something django doesn't know about the templates and the static folders yet so in the settings py file i have to append that's installed apps with a graph app and then the there's list i want to append with a new path join path method and gets the templates name of the folder as an argument and then somewhere at the bottom i am creating a new global variable static files theirs it's a list that gets almost the same element a new path to the static folder now in the base html file i want to load the static filter load static and somewhere at the bottom but before the closing body tag i want to paste here a link to the script to the main.js file src attribute will get on the following value static and the main.js as an argument okay then in the root urls py file i want to create a new url pattern first of all i want to import the include function and my new url pattern will be the following it will include url patterns from my graph app and its urls py file now i have to create urls py file in the graph folder from janga heroes i am importing the path function and i want to create the url patterns list and the handler of all requests to the root url address will be the index function that i want to import from views model import index let's create the index view i am opening the views.py file and here i am creating the index view that gets the request object as an argument i want to render my base html template just place html and the context dictionary have the text key and some some value let's test it let's restart the server i got an exception let's check my urls url patterns a typo okay i've got an empty page because i forgot to use my text variable let's say it'll be h1 header with the app id and here i want to use my text variable the key of the context dictionary and let's open the inspector the console tab and we can see the hello world from our main.js file okay it's working nothing special the next step is to install the django channels and integrate it to the project let's install it now i have to append the installed apps last with the channels then let's open the asgi.py file and i have to modify bits the definition of the application variable i have to import the protocol type router from channels routing protocol type router class that will check the type of the connection the application variable will be an instance of the protocol type router that gets a dictionary as an argument http key and http key will get as the value the results of the get asgay application function okay and then again in the settings dot py file i have to duplicate this line and then i change whiskey to asgay real time graph the application variable is defined in the asgi dot py file so i have to use here the ascii instead of the vizki save let's restart the development server and we can see that the ascii development server is started okay then i have to define a web sockets a router and the handler like we usually do with the core jungle apps let's start with the router we can define in any file we want but the preferred way is to create a special routing dot py file so i want to create in the graph folder a new file routing py and the idea is absolutely the same like for core urls py files i need to import the path function and then i'm creating the ws websocket url patterns list and it will have only one pattern ws web socket graph for example trailing slash don't forget the trailing slashes for jungle urls and the handler in django core such handlers are called views but in django channels they are called consumers so let's say that the handler will be graphconsumer that i have to import from consumers file that i will create a bit later import graph consumer so let's create the consumers module and i have to import the web sockets class from channels generic web socket import web circuit consumer and my graph consumer will be a subclass on the web socket consumer pass for a while and now i have to use this serial patterns i just copied on this name and i need the asgi dot py file again and here i have to create a new key for the dictionary that gets the protocol type router class websocket key and it will be an instance of the auth middleware stack class that i have to import as an argument the auth middleware stack class gets an instance of the url router class that i have to import url router from the channel's routing model and in its turn the url router class gets our ws url patterns list that i have to import to from graph package graph folder from the routing model i am importing ws url patterns list first of all django channels checks the type of the connection it checks the protocol type whether it is an http connection or a websocket connection if the connection is the websocket connection it will be given to the auth middleware stack to identify a user i don't use users here so it will be anonymous lazy user object it's almost the same like jung does with its own oauth model after that the connection will be given to the url router class that pass it to the consumer that was defined in the ws url patterns list let's back to our graph consumer in the consumers model and here i have to override the only one method it will be the connect method this method will define what have to happen when the jungle channels will get the incoming connection and here i want to accept the incoming connection from the client from the browser so i just call in the accept methods the connection is accepted and established so i want to start messaging to the connection i want to randomly generate integers and then send them in a json object so let's import the json library random function from the random model and from the time model i want to import the sleep function and here i want to start a for loop for i in range 1000 and then i'm creating a dictionary with the value key and the value of this key will be a result of the rand int function that will generate integers from minus 20 to positive 20 then i want to serialize this dictionary to the json object json dump as dump stream and this json object i want to send to the other end of the connection and i want to sleep one second now i need the client so let's close it okay and in the main.js file i want to define an instance of the websocket class and then i have to pass into the websocket constructor a url address to send requests to and the url address should be the same as the one that i defined in the ws sorry ws url patterns list so the url address will be ws websocket localhost 8000 ws graph and trailing slash right like here then i have to define the on message methods socket variable on message it's a function that gets an event from the browser i want to get the jungle data jungle sends json objects so jason pars he and i need its data attribute let's print it and now let's get the h1 header by its id and change its text so document query selector app id inner text property and gets a new value jung data and i need its value value attribute because here i used the value let's test it let's restart the server unexpected response code 500 it means that something wrong with our jungle consumer maybe or router the consumer looks fine let's look at routing py file and i forgot to call the as ascii method now it should work okay and it's working and now if i open the seconds tab and make a request to the page i don't get the page so i have to modify my code to get the synchronous behavior to get the asynchronous behavior i have to get a new instance of my graph consumer class for each new client and i can achieve it by using channel layers channel layer is an ordered first in first out data structure it's a queue of messages that this data structure receives from its clients from the producers and for every message on the channel in this queue in this data structure django will call the assign consumer in my case for each message in the channel django will call the graph consumer class so to use the channel layer i have to use a radius the in memory database you have to install it look at the website radius io there is the download section and the full ubuntu-based linux distributions they have ppa and they have also something for mac and i don't sure about the windows but i know that somehow the radius can be installed on windows machine so you need to have the radius installed and now let's install channels redis package channels readers okay now i want to start the radius server we can see that it uses 6379 port number the next step is to define the channel layer variable in the settings py file so let's open it and i want to define it here below the databases because they are similar channel layers it's a dictionary and we can specify here many layers like we can use several databases but the default layer will be enough so default in lowercase it is also a dictionary that has the backend key and here channel redis core radius channel layer and then the config of the redis server it's a dictionary too with the hosts key in lowercase it's a list of hosts i'm using localhost 127.001 as a stream and then i am specifying the port number 6379 this one and that's all then in the consumers py file i have to import the async websocket consumer async and so the graph consumer is a subclass of the async websocket consumer the body of the connect method will be almost the same but the connect method should be according i have to use the async keyboard and to call any functions from the core routine i have to use the evade keyboard and wait here and a wait here because here i'm calling the except method and here i'm calling the send method and then the sleep function i want to change to the sleep function from the async io model and that's all evade here too and it should work let's test it server error maybe i should restart the server okay it works and just restart my django development server it's working let's open a new tab and it's working too another one okay it's fully asynchronous app now let's add the charger as library to the project let's open charging as org website let's get started and i want to use this object this definition of object but first of all i need to include the charges to base html file so i want to use cdng as website and i want to use a minified version and somewhere here script src attribute gets this value okay now let's copy the canvas tag here i want to use height 200 pixels okay and then i want to copy all this code the definition of the chart object and i want to paste it here somewhere at the top first of all i want to take away the javascript object this object to a separate variable let's define it for example let's say it will be graph data variable and copy this object here then i want to delete the content of the options object let's delete the border color it's not necessary let's delete all the background color if you want you can leave this color i want to use the blue one and the opacity will be 50 percent let's say the labels will be months and the type of the graph will be line then i want to use this dictionary this object here and now let's put the data that we received from django to the charges object as you can probably guess we need to manipulate the data list with this data in the data objects in the data set list to get smooth transitions firstly i have to get this data list all list then i have to read off the first element and then i have to append the jungle's data to the end of this list after that i have to assign the new list to the data attribute of the dictionary in the data set so in my own message method i'm creating a new variable let's say it'll be new graph data and then i need to get the graph data object data dictionary then i have to get the data set list data sets it's a list and i need the first element this dictionary and i have to get the data list data to get rid of the first element i have to call the shift method and to append to the new graph data last the data from janga i am calling the push methods and passing into each jungle data its value attribute and then i am assigning to this last a new value new graph data new graph data list and then i am calling my chart my chart it's a an instance of the charts class i'm calling the updates methods and i can delete this line let's test it it's working let's open a new top it's working too that's it if you like the video please leave a like and subscribe to the channel thanks for watching
Info
Channel: Red Eyed Coder Club
Views: 9,199
Rating: undefined out of 5
Keywords: python, django, django channels, django channels tutorial, django real time, django websockets, django tutorial, django websockets tutorial, django websockets example, django real time application, websockets app, django real-time, django channels project, django real time graph, django chart.js, django chart, django websockets real time, django chart.js app, django chart.js example, websocket django, django socket, django websocket, django charts, red eyed coder club
Id: tZY260UyAiE
Channel Id: undefined
Length: 31min 16sec (1876 seconds)
Published: Fri Dec 25 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.