Django Middleware

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello my name is xander welcome back to django core this is a first look at django middleware this tutorial has seven topics it's all supported by code examples you'll find a link to the code repository in the video description here we're going to start off by talking a little bit about django middleware when you might want to utilize it and just familiarize yourself if you haven't already done so with django middleware and then we move forward having a look at boilerplates activating middleware and then move on to middleware hooks at this point we'll try and build an example of each so we'll look at the process view exceptions template process response and then we'll finish up with a an example of capturing user data the example which you might want to just skip to utilizing the video timeline we're just going to build a simple example of capturing user data in this case the user's operating system and then we build out an admin area for it for the data and then display the data in a graph so here for example 59 users or visitors who have come to the website they're using a windows operating system and we can simulate more data by just refreshing this a few times you can see now we have 67. so let's first take a look at the definition of middleware in the django documentation so django describes middleware as a framework of hooks into the django's request response processing it's a light low-level plug-in system for globally altering django's input or output so much of this might not make sense to you now but hopefully by the end of this tutorial we'll have a look again and hopefully at that point we have a better understanding of this description so let's start by recapping a typical http request response cycle the client opens up a browser on their computer or their laptop or their phone and then they request a web resource so they want to connect to our website which is running django so they type in the domain name and a http request is created inside of this http request will be the domain name in which we're trying to contact so that information will eventually get its way to our web server and our web server will then handle where that data needs to go in this case it will then push it to our django application and at that point django then needs to match the url which the client has typed in to a view so if you are familiar with django we know that these view we have views and they're connected to urls so a url is attached to a view so in this case the url is matched and then processed by our view now our view might be connected to a database and templates and eventually we send back a http response and that might include template information and to our web server we should then eventually get back to our clients and then of course the client would then be able to view or see the web page in their browser so let's think about middleware as applications that run before the view processing in a django request response cycle so based upon this example again the client will request a web resource that will be sent to the web server and then the web server will be attached to a django application so django would take that http request through the middleware each application in the middleware that's specified in the middleware settings and then eventually the data will then be processed by the view so once the view's finished processing it will return a http response and that data will then go through the middleware applications once more so the request to confirm the request will go through the middleware twice it'll pass through the middleware twice so based upon that we can build middleware which can process or react to a request or once the view has finished to the response so you're probably all too familiar with the settings file of your project now in every settings file you're probably going to find a middleware section now this middleware section describes all the middleware that is currently activated on your django application so this is the default list if you start a django application utilizing the django admin command now you can see the order that's been provided initially now this is the order in which data will pass through so the http request will pass from top to bottom and then the http respon response will go from bottom to top so that's the order in which data will pass through and that's very important looking at some of these different middleware here and what they actually perform because some middleware here will actually be dependent upon other middleware to be perform actions first for example now although django provides us this middleware by default we can actually remove all this django will still work to a certain point but it isn't recommended we do that for security reasons so it'd be well worth your time having a look at these middleware in a little bit more detail now it would take me a rather long time to explain each one of here but if you just head over to the django documentation if you do have a little bit of time go over to 3.2 in the middleware section and have a look at some of these middleware and just familiarize yourself with some of the options and features that they provide although you might not be doing it now eventually you might be building middleware which is dependent upon some of the functionality that the existing middleware provides so where you place your middleware in that list of middleware may be very important what you will find looking at the documentation is there's middleware that isn't applied by default which we could activate obviously security middleware is there by default the locale middleware is very interesting enables language selection based on data from the request that isn't activated by default and the gzip middleware also so this is a middleware which can compress content for browsers that understand gzip compression and that can help speed up the delivery of data to the user so so far i've explained the idea that the http request from the client will pass through each of the middleware in order based upon what's defined in our settings file now each middleware will take in the request and then also it would then need to pass that request over to the next section or the next middleware in the list all the way down to eventually the view so middleware can also return a response directly instead of forwarding the request further down the chain so this example here the csrf middleware you may have already experienced a csrf problem or error in your application so here they have the ability to return a response directly without forwarding the request to the view this type of feature is quite a powerful tool to have because potentially we are protecting our application for any from any malicious requests entering our system so the most common question i get asked about middleware is when should i use middleware the starting point here is to move through the django documentation now you may not understand it all or any of it but it should give you some general idea of the existing middleware and the actions they perform at least at this point you're not duplicating any of those actions so generally if i were to try and summarize where you might initially think about creating middleware is when you want to filter requests so the user makes a request and you want to filter that information for some reason you want to inject data into requests and responses so for example the view handles part of the response but then based upon the view outcome you may want to attach more data to it for example or the other way around there's a request that comes in from a user and specific information in that request you want to filter that and utilize that to build more data potentially that you can then utilize in the response probably a very common use case of middleware is to perform some sort of logging or analytics of your pages or generating user analytics from user interactions on your site so let's start building some middleware now i am starting with a basic package here which you can download in the video description so this is the starting code you are going to need a virtual machine so let's just go ahead now and build this up right so that just uh sets up the virtual machine that might take a couple of seconds let's just go ahead and activate all right so let's take a look at the project um it looks like we've got a problem couldn't import django that's because we need to pip install django of course right so go ahead and install django uh normal procedures apply here so there is a small table so let's go ahead and just make migrations and then let's go ahead and just migrate we are going to need an admin user so let's just build an admin user so create super user apologies for the small text so i'm just going to make user admin no email password admin password admin and why okay so now we've got an admin user let's go ahead and build a new project or new app sorry so start app and then i'm going to call this demo underscore middleware right so we're going to need a table here so we're just going to go over to the core and settings i'm just going to add this to my installed apps for now and then in addition to that we're going to need to at some point uh register it here in the middleware and you can see i've already gone ahead and done that so here i've added our new middleware that we're building into the middleware section here so demo middleware is the name of the app and then inside of that is going to be a new file called middleware so let's just uh build this so new file middleware.pie uh obviously it's going to be optional what you want to call it and then inside of that we're going to build a new class called demo middleware so let's go ahead and do that so there's no inputs at this no imports at this point so demo middleware so first up then let's talk a little bit about the boilerplate now if you head over to the django documentation they do provide you two examples one utilizing functions and the other with classes now the functions method of developing middleware i would say that was a very kind of um legacy method to generate middleware you can still utilize and you can port it over to this class-based approach but throughout this tutorial i'm going to use a class-based approach to develop middleware if you've been looking around at other examples of middleware and django you will find the majority of 99 of examples would be utilizing a class-based approach so let's just walk through this so first of all we need the init dunder method right so this is going to initiate our class or to walk you through this boilerplate for a middleware application we start with a class okay so now when the class is instantiated it's going to run the initialization method now here what the init done method is it's a way of when the class is initiated it will then perform some actions so here it might be creating for example attributes or variables that can be then utilized throughout the class so here in fact what we've done is we've taken in the get response so how i like to look at get response is that we're basically telling django that this application or the code that it's just about to run is part of the middleware processor is part of a middleware application so each of these middleware apps will perform actions and then basically tell django that they finished and then the next one can then go ahead and perform its action so here looking back in the code we've essentially just told django that this is a middleware application and it's now we're now ready to run the code now in order to tell django that we've finished uh dealing with the middleware in this application how i like to look at it is that we basically just need to return this as a response so here we're going to set up a variable here get response and we're going to pass in the get response and then when we finished everything we're basically just going to return that so next up what we're going to do and the second method here is the call so this is where we're going to perform our actions um or we're going to um set up our code to perform actions in our middleware right so this eventually will this takes in the request so we can deal with the request information and then we're going to pass that in the response and then basically just tell django and let it know that we finished so we're going to return the response so to summarize initialization this is a one-time configuration and initialization area for variables for example so we then have the call so in here we're going to perform logic execute logic potentially on the request and before the view or other middleware is called so you can see that we brought in the request information and then once we've done you can see now we're going to return the response um back to django to let it know that we finished this middleware sequence and to pass it on potentially to the next middleware application or to the view so now we have our boilerplate active we can now go ahead and activate our middleware so we've partially seen this already in our core application now your applications might reside in the core so this setting will be slightly different potentially but here in this instance the applications are in the main uh the main directory so i'll go into my core settings and here you can see in the middleware at the bottom i've placed the new middleware so this is demo middleware that's the name of the application middleware is the name of the file and then demo middleware is the class name we go so that's pretty much it for activating our middleware here now let's just have a look here so i've gone ahead and just added a print here so we're going to print to a terminal so what this is going to mean every time someone visits our web page this middleware is going to be initiated through the get response and then we're then going to run this print which is going to print to the terminal so i've got the server started i'm going to press refresh and you can see now it says hello welt so now we have some information which is going to help us understand the description of middleware in the django documentation this is a system for globally altering django's input or output so based upon that simple example here any web page that we go to or any part of the website that we visit that requires a http request response cycle our django middleware is going to be initiated so now we've built our first middleware application let's now have a look at the middleware hooks and these are optional methods that we can utilize within our middleware so not trying to draw this out but it's important for us to understand these basics for us to fully comprehend and understand where and how to utilize the methods in our middleware so here we've seen so far we've utilized and we set up the initialization and call okay so those are two methods that are required so here i mentioned three hooks or optional methods that we can execute at different points of the view request response lifecycle so let's take a look at when our functions and methods are called in the request response cycle here we have first of all the process request so that's the request data that can be utilized before the request gets to the view and in second to that we have the optional which is process view so we'll take a look at an example of that shortly but this allows us access to the view before the request gets to the view so called during the response cycle here we have process exception so here if the view raises an exception we can then utilize this as part of our middleware to perform actions our third optional method is process template response this allows us to add additional context to the template before we pass it to the user and then finally the process response so let's start off then by looking at our process view so this is a logic executed before call to the view this does give us access to the view and all the arguments etc so this is a very interesting function or method to utilize so we can see what's being passed in here the self request so we still have access to the request but we also have access directly to the function so from here for example we can access information about the the view through the view func here so let's just print for example let's just get some information about the view so let's go for view name and then let's just pass in the view underscore front and then let's just get the name so this is going to return the name of the function that the request is trying to access so let's just take a look at this so our application here our bank app here um it has a url um which i think i've just set up here so the home url here is pointing to the process payment view so in our view here we have a process payment view so when we go to the home page this view should be initiated so what we should return here is what we should print out in our terminal is the name of this view so let's just have a go so refresh and there we go so the view name is process payment so should we want to access the arguments or quarks for our view we can do you can see that we've uh we're going to utilize view args and view cogs to do that so i could provide some more examples here but hopefully you get the general principle of what this is providing it's providing access to the view before the request hits the view and this can help us access and maybe we can perform some checks on the data on the request before it hits the view so maybe that's something we would want to use process view for maybe in later tutorials we can have a look at this in a much more detail and give you something more of a concrete give you more of a concrete example of utilizing process view so let's take a look at our second optional exceptions so this is going to provide us a way of capturing exceptions from the view remember that this is part of the response cycle so the view would have been processed and we're now capturing any exceptions so you might be wondering what exceptions exist when would this work well let's just go ahead and access the shell and just get a list of all the exceptions um so from django core import exceptions and then from here we can then generate a nice little list and then print them out there we go so these are all the exceptions um that would initiate our process exception method here so it can be difficult trying to simulate this so let's go ahead and just build our own exception so just head over to the bank view file here i'm just going to create or raising a demo exception i'm just going to call that demo exception and that's then connected to a class here called demo exception right so there's no imports here so here i'm just generating a demo exception now that's going to be raised before the return so that's going to simulate our problem so let's just go back to the middleware here now in our middleware let's go ahead and create a new variable here in the initialization uh so we've created a new variable num exception zero we're just going to record how many exceptions um that we find so what we're going to do every time there's an exception let's go ahead and just increment that by one for example and then we'll just go and print that out so for every exception that we receive we're just going to keep a running order of that okay so let's go back in and i'll just refresh so i should now receive an exception if i had the server turned on there we go so demo exception so every time i run this we should be incrementing and we have here an exception count of four a few more and you can see now it's gone up to seven of course we could do the similar type of action on the on the requests so for example we set up a separate variable here for um the amount of requests that we've received we can then go ahead and in our section here we can add or increment our number of requests that we've received and print that out too so for every request is i'll just do a few here um it's going to increment the number and we can now see um that we've still got the exceptions so requests handled so far 12 exception count is 12. right so let's just turn off our exception here and let's just go for this okay and you can see that we're going to get the increment here for request handled so far so let's take a look at a simple example utilizing template context response so here this has been utilized on the response it allows us to add additional context data to our template for example so i'll just go ahead and tidy this up we'll go back to the the template boilerplate right so here the process template response so let's just set up some data um up here all right so we're going to set up some data um just a simple message with a warning there's no more ink in the printer right so that's going to be our context response okay right so let's go ahead now and set up this response so here we're going to collect that um context response and response.context data that's going to be our new data so what we're doing here is we're creating if you like a a new piece of context that we're going to pass to the template that we can utilize to render on the template and that's going to be accessed through new data so we're going to be able to access the data that we set up here at the top through new data on our template so let's go ahead and just return the response and now what we're going to need to do is collect this data on our template um so in our templates here in index so i'm just going to create a div placeholder here where we can output that context data and then we're going to collect the data so new data we're going to collect that information so that we can then utilize it so in our script here we're going to get the uh the data the context data and that we've set up here by name okay new data and then we're going to go into that data and then i'm going to look for the message so let's just go back to my middleware so i'm going to select the message and then i'm going to print out the the warning set message dot warning so that i've just basically drilled down to my data where i wanted what i wanted to print out so once i've done that i can then go ahead and for example document get element by id template response i'm just going to inject the message into this development here and it should then be displayed on the screen so when i refresh now you can now see it says there is no more ink in the printer so that takes us to our last example so now we're going to capture from the request the user's data so here we're going to try and capture what operating system the user is currently using and then we're going to develop a database to capture and record that information and then in the admin area we'll then create a graph showing the data that we've captured so this is what the final outcome is going to look like so key to developing middleware is to understand what data is stored in and generated in the request and the response so just looking at our browser here and going into the console i can go over to network and then just refresh so if i have a look at the data that's generated from my request just just draw this up here i can see that my request headers there's information here in the request heads i'm sending across to the server so let's just go over to google.com and just do the same thing again so i just refresh this page so i've got the network open here let's go to the top my request so down here i can see the request headers so this information here is being passed in the request so if you're wondering what data can be collected from the request as it travels into the server and then the data that we can capture either in our middleware or in the view this gives us a good indication of the type of data that we can collect in the request headers now also here we have the response headers so this also gives us some interesting information potentially of information we might want to collect or have a look at analyze before then is sent to the user so again just to emphasize it would be useful for you to read through the uh http risk request and response cycle to get a better idea of um how that is working and what type of data you can collect so let's just tidy this this back here to our our template or boilerplate so let's just quickly move through and have a look at some of the data that we could potentially collect so here i'm just going to from the request uh just set out a number of different prints here right so first of all is a path so this is going to give me a return so let's have a look at the response so i just go ahead and refresh my page so here i'm going to collect a number of different items so first of all the path so that's going to give me the path for the page so in this case it's just a root directory so slash is returned so that can be useful because here i could utilize that data to build some sort of counter so for every page i could build a counter for that page so i could detect what page has been requested and then update the database to correspond to the page that has been viewed so that's request par for example now i can also drill down to headers request headers so that is uh referring to if we go back here and press f12 and network and refresh this is referring to this data here request headers so for example i could access the host or cookie or connection so i can utilize these key data points here to collect this information it might be useful so for here for example and the user agent this is telling me that this user is using windows for example so here i've selected host and you can now see i've outputted the host ip so accept language so these are just other examples except language so i could maybe do some filtering based upon the language setup of the browser um and that could give you an indication of um how to display the page to the user and the different languages i may be able to swap over languages based upon what the browser has been set or defined to the languages that it's been set to here i can get for example the request method so this drills down into meta so this is a separate set of data now that i can draw from the request the metadata so again you'll find it online if you just type in request meta data http request metadata you'll find a list of all the different data i think the django documentation also has a page for this and it details all the different metadata that you can collect so here's the request method get post delete update for example and then finally the user agent and you can see the data here has given me um is giving me an indication of what operating system the user is using so we can just um see that an action in actual fact um so if i were to for example let's just bring this down a bit if i were for example to switch over to uh to say a mobile and then refresh you can now see it's telling me that linux android is being utilized and then i can do the same thing there for iphone it looks like an iphone is utilizing so you can see potentially the information we could collect there regarding their the user's operating system so of course we're going to do exactly that for our last example here so let's just keep this in mind the http user agent that's going to be useful for us to identify what operating system the user is currently using right so let's now build this up so i'm going to create a a new function here i'm going to call this uh just stats for example i'm going to take in self and then for example os info okay right so here what i'm going to do is just set out some simple a simple if statement um if else if else statement which is going to have a look at the data that we collect from the request meta the http user agent and i'm just going to detect certain words so if it's a windows operating system windows is going to appear in this string if it's android we've seen our iphone you can see that the keywords are going to be in this string so we're just going to capture that and for each one that we capture we're then going to update the database corresp to correspond to the operating system that the user is using so let's just go ahead so if windows is in the os information so we're going to pass that information across um then we're going to then just update the database so here i'm going to be utilizing uh f function so i need to bring that in now i haven't made the database yet but this is how i'm going to set it up so there's going to be a field called win for windows and i'm just going to increment that by one anytime we see windows in the in the http user agent information right so next up then will be mac so i'll just use an alphys if for mac same thing again i'll update the new field called mac and then iphone same thing again and then for android and then else we're just going to update a field called other or oth and there we go so that is a simple sequence there where we're going to capture what's inside of our http user agent information and then we're just going to auto increment our database right so we're going to need to pass that across so let's do that so um let's uh run the function uh stats and then just send across a request information remember that information is going to store what we saw earlier uh just to kind of reiterate that fact so we're going to it's going to be storing this user agent information here which is going to identify um keywords iphone windows android now we probably don't want to update statistics if for example the user has gone to the admin area so we don't want to record admin views so what we can do is just a simple if statement here so if the word admin is in the request path now the request path is going to produce [Music] for example here in the admin if we were to go to the admin the request path is going to include the word admin in the request path so that means we can then filter that out from the request path and then if the request path is not in the admin we're going to run our stats and update our database so our database is going to be relatively simple here we're going to have what five builds so i'm going to call this new stats that was the name of our database new stats now here in the middle where i hadn't actually imported our model so let's also add our model in so it's called new stats apologies is um the flow here if you're not used to this the flow might be a little bit out but you can see we've created a new model here so let's just go ahead now and make migrations and migrate so we've now built this table it's now ready for us to utilize so let's just go over to the admin and let's just uh set this up so uh what we're gonna do here is let's first of all just register so from models let's import new stats and then we'll just go ahead and register this now just prepare this i'll use the decorator here and i'll just pass this for now so we are going to expand on this shortly and with this new class this allows us to provide some additional uh customization of our admin section so we're going to need this shortly so i've just registered it for now and let's just go ahead and start our server okay and we just make sure this is all working so i have already set up a user admin and admin and we've got this new table here new stats there we go so let's add a new stat um and we can add some numbers straight away here okay right so let's press save and there we go so we've got a set of um set of data here for each operating system so now we need to perform some customizations here for our admin area so that we can enter or add the graph up the top now this is pretty simple in actual fact the first thing we need to do is create a new template right so in templates let's create a new folder now what we're doing here is we're just following a pattern that's set so we know we want to build an admin template so we call this admin right so now we need to follow this path so admin demo middleware new stats so that's the the structure here so inside of admin we're going to have a new folder called demo middleware inside of there we're going to have a new folder and that is called new stats so that's going to provide a path for django to utilize for us to then add a template so let's just add a new template this is going to be called change list right so let's create a new file called change underscore list dot html okay so now we're going to override this template just by adding a title and from there we can see where we're working we can expand and add our graph so back in the code here then this is in the changelist.html we're going to override or extend admin changelist.html and then we're going to load any static create our new block and we're just going to add hello world so it just appears just underneath the change new stats just so we can see where we're working and then the block super this is a reference to all this other um all these other elements here that you see on this template right so with that done let's go ahead and end the block and we'll just run that now so with those changes remember we need to go into the main section of new stats here and we can now see we have hello world so there's two steps left first of all we need a way of actually getting our data from our database over to the actual template so that we can display it and then secondly we need to generate a graph of some sort to actually build the chart we're going to use chart js for no particular reason this is just a very simple tool to utilize to build charts so it has some great samples and also some great documentation to run through if you did want to utilize this for any other of your applications right so let's just go ahead and build the framework for this so we're just going to remove our block content and all the other items and rebuild this right so we're going to create this block called extra head here and then we're going to utilize block super right so if you haven't used block super before if you need to get the content of the block from the parent template this will do the trick so the idea here is that we're trying to add contents rather than completely overriding the template so let's move on to creating the link now to the chart.js so here we're going to bring in the css and then also the js bundle so that's going to obviously allow us to run the chart that's all the javascript for the charts functionality and the css and now we can then um think about where we're going to put our chart so here we're just going to create a div here element canvas and we're going to give us an id of my chart right so that's where the actual chart is going to be placed right so once we've done that let's start now kind of initializing and connecting this up so it creates a new variable here document.elementbychart so we get the canvas and we kind of then are going to prepare that for us to then essentially put the chart onto the canvas so now what we can do um here we're going to render the chart so uh chart new chart we're going to bring in um our canvas if you like it so that we can prepare and now we're going to define what type of chart we want to create so in this case it's going to be a bar chart now head over to chart.js obviously there it's going to provide a lot of other examples maybe you wanted to turn this into a pie chart for example so that's the type of chart that we're going to run and we're going to need some data for this so i've created some labels here we're going to have a y and x asset x axis so these labels here correspond to the x axis um so we're going to have five sections along the x axis of our bar chart uh windows mac iphone android and other right so now we're going to need some data so there's a label so this is the label for the chart so i'm just going to call this um visits number of visits per operating system in this case and then i'm just going to add some data for now so we're going to swap that in a little bit by grabbing the data from our database and putting it right here but we're just going to add a template um or some placeholders here of data so that we can just see this in action and now we can just go ahead and define the colors so this is the background color so these here um refer to we have one two three five x uh five um along the x axis here five chart sections so these colors here will correspond to each one um so i've only added two here you could go ahead and add five if you want and then you can also change for example the border color so you can have a separate border color for each of the bar chart sections right so once that's done you can also define the border width if you want and we can also then add some other options now by default the y-axis won't begin at zero so i've just gone ahead and head along the y-axis here and i've just changed it so it begins at zero so our um a y and x i will meet at zero else what you're going to find is that normally what happens by default the chart shows the lowest quantity um and it doesn't actually then show as a bar chart it's just the lowest quantity so go ahead and have a look for yourself but um define that as zero so let's take a look at what this looks like so if i refresh you can see one two three and four five there we go that's the data we have in place you can see these are grayed items because i didn't color them i did color the first two so you can go ahead and do that we've got number of visits up here and we can see that the scale starts from zero right so now what we need to do is get our data from the database here and then get it so it appears in our graph so we need to collect the data that's going to be from the admin area so what we're going to need to do here is to collect the data from our model we've already imported in our model here and then we're going to pass that as um we're going to serializer serialize that um and then we're going to prepare it so we can pass it over to javascript i always try to where possible introduce new django tools and features and this is one of them here so in order to get our data ready to be sent across or utilized by json uh sorry javascript we need to convert or serialize uh to a format that we can then pass over to javascript now here for example i just wanted to showcase the django json encoder so if you are it's likely that you will be at one point um encoding date time this is a great tool to utilize and it's well worth just making a note and when you do start kind of encoding date time this can be really handy to utilize and we are going to utilize it um out of context here to do this so of course we've got other tools django core import serializers to prepare our prepare our data and be before we move it across but in this case i'm just going to use the django json encoder um just because right so now we need to prepare our data so we we're going to collect the data from our our database then we're going to prepare it and then send it across so we can then utilize it on our change list admin template all right so let's go ahead and create a new function here i'm going to call this changelist dot view change list underscore view self request and then extra content uh and now we're going to set up the data so right so now we're going to connect to our our table new stats objects dot and then we're going to utilize annotate and with the values win mac uh iphone android and other so we're going to collect well look at this i guess is that we're going to cycle through the database and then for each item in the database that we find remember there's five tables or sorry five fields in our table and we're going to essentially add um a label against our data i guess that's how i like to look at that so now we've got this in place uh let's go ahead now and well i'll give you an another example here of just utilizing um serializer here so if you did want to just utilize the import serializers to perform the same or similar actions you can do so now we've got our data we're now going to use json dumps so that essentially is a way of converting a python object into json yeah so conv yeah the function converts a python object into a json string so you can see that we're going to build this list um we're utilizing our data that we've extracted from our database so now we've done that let's now pass it back to extra content context sorry so here we're going to pass it through extra context we're going to reference the data as stat data and here we have as json so that was taken like i said our python object into a json string so we're going to essentially pass this across with a reference point of stat data our json string so i do apologize there's a lot going on here and i haven't explained this fully like some people would need for others it'd be absolutely fine for example if you've never used annotate before you probably won't know exactly what's going on there so it's worth having a look at here at that now if you do want to if you're trying to explore this code a little bit further utilize print for example to print out different items on this page work out the data that's actually been moved around once you understand the data types once you can see what data is actually being generated collected and moved around it does make your life a lot easier to work out what's actually happening and then i apologize for those who are experienced and this is just very sim simple and very naive potentially some of this because i'm just trying to showcase other tools here right so now we've got that in place we've saved that so now let's um collect this data now on our template so let's go ahead and create a new variable here chart data now we're going to collect the data okay so now we've got the data passed over and we're storing it now in chart data so let's just go ahead and for example let's just create a new array in preparation and now we're going to create a for loop so we're going to just loop through the data and here you can see we're just going to look for delay the data and we're just going to get the values so chart data zero and it's gonna then grab the values and we're then going to just push those values into our array called a r r and now what we can do is we can utilize this we can remove our data from here type in arr you can obviously name that more appropriately so that's our data now in place so let's go ahead now and just see if this works so if i refresh we all get an error name json not defined okay so the problem here is that i was going to show that i forgot pledges um we need to import json here up top i've just forgotten to return so what we need to do here is return super dot change list view um and then request and then the extra content equals and then it's going to equal our new extra content right so that's essentially going to pass that back to our template now we've got this extra context we're bringing in which is the stat data so now that was then moving across now to here so what we've done is we've just collected that data stat data and then we've now prepared that in a new variable and then we just use this for here to loop through and grab the values from our data and then we've just pushed that to this array here so that we can then just output it here in our in our graph right so when we go back now and refresh we can now see we have some data right so let's just see if this works so we'll just open up a a new window all right so just refresh a few times and then i'll press refresh so you can see that this is going to be a windows remember if i press f12 just refresh remember that the headers here we're sending across oh actually in this case we're sending across iphone one second so in this case here we're sending across um and the user agent has windows so remember we're capturing that or we're looking for that name if we find that name we're going to update so it says 16 at the moment so let's just refresh this a few times refresh again and now you can see we've got 24 visits right so let's just move this into for example iphone so at the moment we've got 11 iphone visits i'll just refresh a few times here um and then i'll go back you can now we see we've got 20 iphone visits so should you need a quick recap remember what's happening here is we are initiating our our middleware we are then utilizing call here to basically collect the request information so here what we're doing if it's admin then we're just going to ignore so if it's not an admin else so if the path doesn't have the word admin in it remember we are basically just checking for that so if they are in the admin we're not going to collect those stats so what's happening now is that we're just going to pass across to our function stats function the request meta http user agent now remember what's inside of there is that information which i've been showing you right here so essentially that information here is being stored there or sent across now this has got the word iphone obviously if i change this to something else like windows it's going to have the word windows in there so what we're trying to do is we're just filtering that out using some if statements so we pass it over to this we pass that data across here um and then basically we're just looking for keywords inside of this string that we've collected in the http user agent data and then basically we're just using the f here to create an update um we're just incrementing by one in the database so that's a database side so remember the admin side what we've done is we've created a database that's been updated so now what we're doing is we're basically just trying to collect that data prepare it um ready to send across so we use json dumps essentially for that and then we send that across as extra context over to our change list template then we've collected that data we've then looted through for the values for example and we put that into array and we've outputted it to our new chart if you have got this far thank you very much for listening and going through that process i do hope it was useful there are times here maybe where i've skipped a little bit or haven't explained fully that wasn't due to me trying to speed up or slow down trying to find that balance between providing this type of content to new users and maybe those with a little bit of experience is quite difficult because this might be considered a higher level an advanced tutorial and i was trying to bridge that gap so that um somewhere in the middle um so that newer users can understand and maybe those advanced can breeze through so again thank you very much for listening i do hope it was useful and i hope to see you in the next tutorial
Info
Channel: Very Academy
Views: 6,502
Rating: undefined out of 5
Keywords: django middleware, learn django middleware, django middleware example, django, django tutorial, djangotutorial, django tut, django 3, django examples, learn django, django beginners, beginners django, django framework, django example, django 2021, python django
Id: EpZOVmEw9Qg
Channel Id: undefined
Length: 56min 19sec (3379 seconds)
Published: Tue May 18 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.