Python Live Chat Room Tutorial Using Flask & SocketIO
Skills:
Tool Use & Function Calling90%Prompt Craft80%Prompt Systems Engineering70%Advanced Prompting60%Agent Foundations50%
Key Takeaways
This video tutorial demonstrates how to build a live chat application using Python, Flask, and SocketIO, covering topics such as routing, template rendering, and real-time communication.
Full Transcript
[Music] foreign I'll walk you through building a live chat application using python flask and flask socket i o let's look at a quick demo and you can see what you're going to have finished and built by the end of this video so I'm going to start by creating a new chat room here by clicking on create room this gives me a four digit code for the room if I copy that and paste this here and then enter a name something like Joey and then I go with join room you can see that I joined the room and on the left hand side here it says Joey has entered the room now I can start messaging so I can say something like Tim is the best okay I can send that and then see it comes in here say something like I agree obviously this is happening in live time and notice that I don't have to refresh the page to see the new messages now if we add additional clients more people obviously could join the room I haven't set up any limit but you could do that if you want to and you can have other chat rooms happening in parallel with a different message log one also important thing to note here is that if I refresh the page what happens is I actually disconnect from the chat room or the socket and then I'll automatically reconnect but I'll still have a history of all the messages because we're saving those so notice if I refresh here what happens is it says that I left the room and then it says that I joined again because I left and rejoined instantly and then it says here that I've entered the room and just in terms of the message history we can see everything that was sent now this is a very cool project you're going to learn quite a bit about flask and flask socket i o I will mention that this is not for complete beginners I am going to assume that you have some python experience and if you don't have that or you're just looking to get better at software engineering and programming in general then check out my course programmingexpert.io and if you're interested in web3 and blockchain Technology I have another course blockchain expert which will both be linked in the description with that said let's get into the video and learn how to build a live chat room application using flask flask socket IO and python alright so I'm here in Visual Studio code which is where I'm going to write all of my code I'm using python version 3.11 but feel free to use any version that you want and the first thing we need to do here to get started is install flask and install flask socket i o so I'm going to copy the command here pip install flask paste that into my terminal and hit enter and then I will do the same with the second command here even though I have both of them installed already now for some reason this pip command does not work for you I will leave two videos on the screen that show you how to fix that command 1 for mac and one for Windows okay so now that we've installed flask and flask socket i o we're going to start by creating a very basic flask web server and then we're going to create our different HTML templates and all the other stuff that's involved now to give you a very quick overview of exactly what we need to do here we essentially need to use sockets which are kind of a live way of communicating rather than refreshing the page or saving stuff in a database to transmit messages between different chat rooms and different clients so we're going to have what's known as a socket server which is going to be running on our flask web server and then we're going to have different clients which are really just the web browsers that connect to that server they're going to send a message to our server our server is going to look at what chat room they're inside of and then it's going to transmit that message to all of the people that are in the same chat room they're going to be listening for that message on the front end so in JavaScript and then they're going to be displaying that on the screen so it's a super you know 10 000 foot view of what we're doing here but there is a few setup steps involved so just follow along with me we're going to get a basic flask web app kind of set up here and then we'll do all the socket stuff which will come after we have kind of the main I don't know boilerplate code written so the first thing we're going to do here is we're going to say from flask and this actually in lower case Import in uppercase flask and then render template this is what we're going to do to render the different HTML code that we need we're then also going to import request if I could type that properly session and then redirect next we're going to say from and this is flask underscore socket IO we are going to import join underscore room leave underscore room send Emit and actually we don't need emit we just need sensory and then socket IO with a capital i o then we are going to import random we're going to use this to generate those random Room codes that you saw and we will say from string import and then this is going to be if I can spell this correctly ASCII underscore and then uppercase which are all the available characters we can choose from when we are generating a room code next we are going to initialize our flask application to do that we're going to say app is equal to flask underscore underscore and then this is name underscore underscore which is the name of our python module then we need to configure our flask app so we're going to say app dot config and then we're going to say our secret underscore key in all capitals is equal to and you can just type in something random here obviously in a production environment you would want this to be a more secure key but in our case we're just doing development so it doesn't really matter what we have there next we're going to set up our socket i o kind of integration so we're going to say socket IO is equal to socket IO and then we're going to pass our flask application and then at the bottom of our program here we're going to say if underscore underscore name underscore underscore equals underscore underscore main underscore underscore in a string we're going to say socket IO dot run our app and we're going to run this with debug equal to True okay so I know I just wrote a fair amount of code there but this is the basic setup for any flask web server or application if you're not familiar with flask this is a lightweight web framework used in Python to generate websites in our case we're creating a website obviously using flask and we're implementing all of the socket stuff in our kind of flask back end and then all the front-end code you see will be what we write in HTML and JavaScript okay so all this is doing again it's just kind of initializing everything setting up our main application and now if I actually run this code by hitting the play button or typing Python and then the name of my file which is main.pi you'll see that it starts a development web server here and unfortunately my terminal kind of messed that up so let's rerun it here and notice that we're running on 127.0.0.1 colon 5000. this is otherwise known as localhost Port 5000 so if I go to a web browser and I open this up you'll see that we actually get some output here it says not found the requested URL was not found on the server and that's because we've yet to create a root so we don't have anything kind of being returned when we go to this page but our web server is indeed working and running one thing to note since we put this in debug equals true that means any change that we make to our web server that does not break any of the code will actually automatically refresh so we don't need to continually keep re-running the server but sometimes you'll see that the server will stop because we do something where it kind of breaks it in that case yes you will need to rerun it so for right now I am just going to stop the server by hitting Ctrl C and once we get some more code done we will rerun that kind of leave it running and then we can continually check the progress by looking at our Google Chrome window okay fantastic so the first thing that I want to do here is create the two routes that we're going to have for our website so the first route is going to be our home page and that's going to be where we go to and we want to connect to or create a new chat room and then we will have a room page which will be where we go to when we want to join the chat room so to do this we're going to type at app dot root and for our root we're going to do slash it's just the home page root and we're going to say methods is equal to and we're going to put in all capitals here post and get inside of a list we then are going to type a function so Define home and for now we're going to return render underscore template we're going to render the home.html template which I will discuss in a second so in case you are not familiar with flask this is how you set up different routes you use The Decorator syntax which is at the or the at symbol sorry and then app which is the name of our application you type dot root and then you put whatever the root is going to be so in our case it's just slash if you wanted slash home you would type slash home now for the methods these are the allowed methods that can be sent to this root by default you just have get which means you can retrieve whatever this returns however I want to have posts as well which allows us to post data to this root because we are going to be posting if we are creating or joining a chat room we need to kind of send that data back to this root you'll see why we need that in a minute but for now if figured we'd just kind of write in this post and get what do you call it data for now okay perfect so inside of here we're returning render templatehome.html we've yet to create this but essentially that is going to render a template file which is really just our HTML code which will be displayed on the screen so now we need to actually write a bit of HTML code so I'm going to make a new folder it's very important that this folder is in the same directory as your python file and that you name it exactly as I have here which is templates it needs to be plural and it needs to be templates if you name it anything else this will not work and just let me zoom in a little bit here so you guys can see this a bit better okay so name it templates and then inside of here we're going to create three files the first one is going to be base.html the second one is going to be home.html and the last is going to be room.html okay so we will fill those in in a second we're also going to create one more directory here called Static and inside of static we're going to place any static assets like our CSS style sheet so we're going to create a new folder CSS and then inside of that folder we're going to create a style dot CSS file I'm just setting up these initial files so we don't need to create them later on we will fill them in in a few minutes so again you want templates you want these three files base home and room and then you want a static folder make sure it's called Static and it's in the same setup that you see here another folder called CSS and then inside of CSS style.css if you wanted images or other static assets then you would put them inside of this static folder very important that you have that otherwise it's not going to work when you try to load stuff like the style sheet okay so now let's go to our base.html file now the way that flask works when it comes to rendering HTML is that you can actually pass variables directly to the HTML code that you are rendering so from this render template function you can pass some variables like chats equals and then you know a list of messages or something along those lines and you can use something known as the Jenga templating engine inside of your HTML code which is kind of a variation of your standard HTML to render um kind of content that is served from the server so see what I mean in a minute but what we always do what we typically do when we're creating a flask or Django website is we create a base.html file which acts as our base template this is something that's going to be like a generic style for the entire website and then for our other templates like home and room we just override parts of the base templates that we can reuse code throughout the entire website without having to rewrite it so you'll see what I mean in a minute when I start writing our code but for now we want to set up a boilerplate HTML document so I'm going to type HTML colon 5. for some reason my extension isn't working typically it gives me an auto completed document but I guess I'm just going to have to type it out here so I'm going to type doctype HTML ML and then we're going to go with HTML we're going to say our language is equal to em we're going to end our HTML tag okay perfect we're then going to create a head tag and end the head tag inside of our head tag we're going to create our meta tags so we're going to have meta Char set is equal to and then utf-8 then we're going to create our title so we'll just call this chat app for now okay slash title then we're going to link to our style sheet so the link to our style sheet we're going to type link we'll end the link tag here we're going to type Rel equals style sheet and then the href for our style sheet is going to be the following make sure you type this exactly as I have it we're going to do two sets of curly braces which indicates a variable in this janga templating engine we're then going to type URL underscore four and we're going to grab the URL for the static directory now actually make sure you do this in single quotation marks otherwise you're going to get an error because you have double quotation marks here and uh you would have double inside there if you didn't change them so make sure it's single quotation mark sorry then you're going to type file name is equal to single quotation marks CSS slash style dot CSS okay so I know that's a fair amount of code there but the url4 is going to generate the dynamic URL for this static directory then we're going to look in the CSS directory find style.css and this is the only way we're able to link our style sheet here inside of our HTML document okay next we are going to put a script tag in here which allows us to use the socket i o module which is something in JavaScript so there's actually a library that we need called socket IO it's used in JavaScript and we're going to use that to communicate with our backend python web application so let me find that quickly the way I can do that is by going to the internet typing flask socket IO alright I'm going to go to the getting started documentation and then notice here that there's some sample code so we have a CDN and then we have this kind of script tag which we'll look at later for now I'm going to copy this first script tag again you can find this by just Googling flask socket i o or by going to the URL that's on my page is fairly easy to find and then we're going to paste it in the head tag here okay if you really want to I'll zoom out and you guys can copy this exact URL uh but I think it's going to be easier if you just go to that website I'll try to remember to put it in the description but in case I don't just go to the page that I have here okay you guys can just find it from Google all right so now that we have this inside of our head the next thing we're going to do is create our body tag so we're going to say body like this slash body and then inside of the body we're going to create a div this is going to have a class name of content and we're going to end our div and inside of here we're going to create something known as a block which I'll discuss in a second so to create the block we're going to do our curly braces and then two percent signs and we're going to type block and then the name of our block which is content and then we're going to end the block by typing percent and then if we can do this here end block for some reason it keeps messing up everything that I'm typing but you guys get the idea okay so what is a block well a block is essentially a reusable part of our code that can be overwritten so when I type block content what that means is that in one of my child templates which are going to be home and root I can write this same thing block content and anything I put inside of that block will override anything that is currently here so this allows us to kind of dynamically inject code into this existing HTML template so we no longer need to rewrite this whole HTML document structure the script tag the link Etc so hopefully that makes a bit of sense but that is why we are writing these blocks okay so now we're going to go to our home template and we're going to start writing some code here so the first thing we need to do is extend our base template and the way we do that is we type percent percent extends and then make sure you have quotation marks here we're going to type base dot HTML okay so that means now we are going to inherit all of the code that exists here and be able to override these blocks so I'm actually going to grab this block I'm going to write the exact same thing I had before so block content and block and now anything I write here will essentially show up inside of this content div so now for my page here all I'm going to have is a form and on that form I'm going to have something that says enter your name create a room or join a room those are going to be the options and the reason we need this inside of a form is because based on what you press in the input data you have we need to receive that on our back end and then handle that so we're going to create a form we're going to end our form for the form we're going to say the method is equal to and then this is going to be post this means that whenever we hit the submit button it's going to send a post request to the root that we are currently on which will be the home page inside of here I'm going to type H3 I'm going to end my H3 tag and I'm going to say enter the chat room like that just a header you can obviously change this if you want then I'm going to make a few divs here I am going to use a bit of CSS styling but I'll try to keep it nice and simple if you guys for the first div block I'm going to have the information for entering a name so I'm going to create a label and for the label I'm going to say Name colon like that and then let's end our label then I'm going to have an input tag and this is going to be a text input for the name of our user so I'm going to type type equal to text placeholder is equal to pick a name we're going to say name is equal to and then name now it's important that you have this because this is what we're going to use to access the value inside of our flask web server so whatever you label your inputs or your buttons with the name field by the way it's very important that use name is what's going to pop up as the key for the data that's in the form data we're going to get when we actually Analyze This post request I know that sounds like a lot and probably is gibberish to some of you but the name is essentially how we identify this element from python so make sure you include name okay so we have name equal to well name then last thing we're going to have here is value is equal to and we're gonna put inside of Double quotation marks or double uh curly braces sorry name now the reason I'm doing this is because we are actually going to pass to this template the name that the user has typed in previously that's because it's possible for them to make a make a mistake story during the form submission if that's the case I don't want them to lose the input that they had previously so I'm going to re-inject it by kind of passing it to this template you'll see what I mean in just a minute now after this div I'm going to create another div here and let's end this just to kind of separate our different inputs for this div I'm going to have a class name which is equal to join and this is going to represent the join button and the text input for the kind of room code that you're going to be joining so I'm going to have an input field here and we're going to say type is equal to text placeholder is equal to room code name is equal to code and then same thing we're going to say value is equal to and then inside of our curly braces and double quotation marks we're going to type code same explanation here as name okay next we're going to have a button we're going to say that the type is equal to submit we're going to say the name of this button very important again that you have the name here is equal to create the class of this button is create and then we're going to say creates a room as the value or the text on the button and then we'll end our button lastly we're going to add one more button down here and this button is going to be type equal to submit name equal to and this is going to be joined sorry I need to actually swap these so we're going to have this as join and the class here as join and then this one is going to be create and actually I'm going to remove this class because I realized I duplicated it here in the div sorry for a bit of confusion there but I just need to switch around the name so this one is join and this one is create and I realized that this now needs to say join a room not create a room because that doesn't make any sense all right then we are going to say create a room and then slash button okay I think that is better perfect so now we have a base template and we can have a look at well what this looks like by running our web server so to do that we're going to run our code python main.pi we're going to go to this URL and notice this is what we get now this is not the best so it does call for a little bit of CSS styling to do that we're going to go to our style.css file and start writing some code so let's go here to style.css I'll try to keep this fairly basic but we do need to write a bit of kind of responsive styling here so actually apologize we're going to go back to home and for our form we are going to actually give this a class because we're going to need to access that class to do some styling so the class for our form is going to be the following class is equal to buttons I know that's not really the best thing to name it but I think that's fine for right now okay so now that we have our class in here we're going to start writing the CSS all right so the first class that we're going to style here is going to be our buttons class which is really that form so we're going to say buttons display is equal to flex the flex direction is column so we align our items in a column rather than a row we're then going to align our items Center and we are going to justify our content Center as well this is probably the easiest way to align things in the middle of the screen you just go align item Center justify content Center and then you're going to align them Center on both the vertical axis and the horizontal axis then I'm going to type Gap is equal to 10 pixels just to give a 10 pixel gap between my different Flex items and the flex items are going to be the divs and the buttons that I have inside of my form so if we look here at home.html we have this element this element this element and this element all inside of here they're going to get a 10 pixel Gap and be aligned in a column all right going back to style.css we also need to style the join div so we're going to say join we're going to say display Flex like this we're going to say the flex direction is row and then we're going to say the width is equal to a hundred percent okay then we're going to say dot create and let's just quickly go back here to home and do we have a class for create we do not have a class for create so I'm going to say class is equal to create button so we just want to add a class to this create button because I want to extend its size to make it a bit larger so we're going to say create dash button and then it's going to be width and we're going to make this 100 and that's actually all we need for this first page styling so let's now refresh our page and see what we get all right so that looks a little bit better but we can obviously improve this and I realize that the way we need to improve that is by adding some styling to this content div so the way that we can do that is we can go here to dot content and for Content we can say display Flex align item Center and justify content Center and that should ideally fix our elements let's go back here and refresh and now notice everything kind of gets packed in here and that is much better okay so I'm not going to explain the CSS too much uh feel free to kind of pause the video and you can copy it in here if you don't already have it but there you go that is going to be our home page now that we have our home page we want to handle what happens when you actually press these different buttons so you'll notice when I press them what happens is actually a post request is sent to our home root here but currently we're not doing anything with that post request so now what we want to do is handle the post request by getting the different form data that's being sent now the form data that's being sent is all of our inputs right and whatever button we pressed so just to note here whatever button you press the name of that button is actually sent through as form data so that way we'll know if we press the join button or the create button from the same form so we're going to have to obviously handle that if we are creating a new room we're going to want to create that room if we're joining a room we're going to want to attempt to join that so to do this we need to go to the top of our home function here and we need to check if the request dot method is equal to post if it is we're going to do something special otherwise we're just going to render this home template now the reason we can use this is because we imported request obviously the method is the type of request to either post or get if it's equal to post then we need to grab our form data so to get our form data we're going to do the following we're going to start by grabbing our name and the way we do that is saying request dot form dot get and then name okay so we have this attribute.form on our request object that has all of the different named input Fields so it'll have if we go back here to home we will have name as well as code as well as join or create depending on the button that we pressed okay so we have name we have code is equal to request dot form dot get and then this is going to be code and then we're going to have join is equal to request not form dot get and then join and then create is equal to request dot form dot get and then create now what I'm going to do for both join and create is I'm going to set the default option here equal to false now if you're not familiar with how the get function works it's going to attempt to get this out of a dictionary so the form object is actually a python dictionary now if you were to just try to access code or name and it didn't exist in the dictionary you would get an error we want to avoid that error so instead we use the safer method which is dot get What DOT get will do is attempt to grab the value associated with this key in the dictionary if that key does not exist it will return none now if you don't want to return none instead you want to return something else you can set the default option which is what I'm doing here so now if join doesn't exist we're going to get false if create does not exist we'll get false if either of them do exist we'll get the value associated with them the reason I'm doing this is because join and create are both going to have an empty value it's just a button so the button doesn't really have a value right it's just giving me the key saying hey this button is pressed doesn't really associate with anything so I need to set this to false just so that when I do a check here in a second we can actually see if we had the join key or if we had the create key in our form there's other ways to do this but I figured we can just do this for now okay so the first thing I'm going to do here inside of my kind of if statement block that I have is I'm going to check if the user did not pass a name if they didn't pass a name I want to give them an error message and tell them they need to need to enter a name sorry because even if they are joining a room or creating a room it doesn't matter they need to give me some kind of name so they need to have that so I'm going to say if not name essentially meaning if the name is empty if they didn't give me a name whatever then I'm going to return render template of home.html but I'm going to pass error equal to and then I will say please enter a name so remember I told you that we can pass data to the template and render it in the template that's what we're doing here we're passing an error variable so now what I can do is I can go to home.html and inside of my form or outside of my form doesn't really matter where we want to do this I can create a UL tag so this is going to be unordered list and I'll just do another Li tag here and inside of here I'm going to put double brackets and then error which will access that error variable however I only want to display this if we actually have an error so the way I can do that is I can type percent percent I can type if error like that and then I can go down here and I can type percent and then end if so only if we do have an error if the error Valley Value sorry is truthy will we render what that error is perfect so we now have the error handling kind of done all right so that's our first check if they don't have a name the next thing we need to do is we need to see if they are attempting to join a room because if they're attempting to join a room but they didn't enter a code then obviously that's an issue so I'm going to say if joian does not equal false and not code then we're going to do the same thing except we're going to return render template please enter a room code perfect okay so now at this point we know that they have a name and if they are trying to join they did enter a code now what we need to do is figure out what room this user is going to be going into if they enter the room then we know the room code and we need to check if that room actually exists if they didn't enter a room then we need to actually generate that room for them so we're going to say room is equal to code like that and that's because we're going to grab whatever's inside of this code variable however we're going to say if create does not equal false so if it's not the default option meaning this key did exist then what we're going to do is we're going to create a new room for them so we're going to say room is equal to generate unique underscore code and we're going to pass 4 here which is going to be the length and this is a function that I'm going to write in one second that's going to generate a unique code for us in fact we can do that now so let's write a function up here I'm going to say Define generate underscore unique code we're going to take in the length of the code that we want to generate and we're going to generate that however before I do that I'm going to say rooms is equal to a dictionary and this is where we're going to store information about the different rooms that we have like the code associated with that room and then any of the messages or people inside of it reason we need that is because we need to see if a room exists for a user to be able to join it and if the room already exists we obviously don't want to generate a code that's the same as one that exists if we're creating a new one so here we'll generate a unique code to do this I can say while true code is equal to an empty string I can then type 4 underscore in range and then the length of our code underscore being an anonymous variable so rather than having something like I I do an underscore because I don't actually care about the iteration count here then I'm going to type code plus equals random dot choice and I'm going to choose from my ASCII uppercase characters this just gives me a list or actually a string of all of the valid ASCII uppercase characters I can randomly choose any of those elements add that to my code and then after my for loop after I've generated one of whatever the desired length is I can say if code is not in rooms this checks if the code exists as a key in this dictionary then I can break and I can return my code down here if it did exist then I wouldn't break meaning I would regenerate another code okay so there we go we have generate unique code that's working now that we are generating the unique code we're going to say rooms at room is equal to and then we're going to create a dictionary here which is members and this is going to be essentially the number of people in the room which is currently zero and then we're going to say messages and this will be all the messages that exist in the room and this will be a list that we will fill in so we're creating this room right so if they're creating a new room we're going to create that room by adding it to our rooms dictionary and we're going to store some data with that this is kind of our boilerplate starting data eventually we will add and change that perfect now we're going to say elif code not in rooms like that then we are going to return a redirect and we're going to say that the room does not exist okay fantastic now the reason why I'm uh doing this here is because if we determined that they're trying to create a new room okay fine we're going to do this if this is not the case if they're not creating a room then they must be joining a room and in that case if they're joining a room and the code that they're trying to join doesn't exist that room is not existent then there's an error right so we need to tell them what that error is now remember though that for all of these different um uh what do you call it cases here where we have errors we still want to persist whatever it was that the user typed in so the name or the code we don't want them to have to type that again so the way that we need to do that is we need to pass along with all of these renders the variables code is equal to code and name is equal to name the reason we need to do that is because we need to pass it back to the template because whenever you send a post request you're essentially refreshing the window so it's going to get rid of anything that they typed and then we need to give back to them whatever they type so we can re-enter that as the value for our input field so if you look here right we have code and we have name so we need to pass that data back in which is what we're doing here from our render template function so for all of these I'm just going to copy this in and obviously we don't need this for this last render template because this is only going to happen if this method was not a post request now there's a few last things I need to do here before I'm finished on line 44 I'm going to write session room is equal to and then the room that they're going to be joining and I'm going to type session name is equal to the username that they typed in now the reason I'm doing this here is because a session is a semi-permanent way to store information about a user I don't want to do anything like logging in or accounts it's a bit beyond the scope of this tutorial so rather than doing kind of advanced authentication we're going to store data in a session again a session can kind of be described as temporary data that's stored on a server the same the session can be manipulated by the server so we can clear it we can change the value and this is a semi-permanent because it will expire at some point in time yet secure way to store user data so I have session room is equal to room so I'm storing the room code that this user is kind of in or is going to be in in a second and then I'm storing their names that I have access to that now through any other requests that they send me so to clear your session data um you usually you have to do that directly from the server I think there's some ways from the browser to force your session data to be refreshed but this is a little bit different than user cookies okay I'm not going to get too much into exactly how the session works but if I say kind of go out of the web browser and come back in like a few minutes later my session data will still be there so between different requests it's stored persistently so that I don't constantly ask the user for a name every single time they refresh the web page same with the room code that they're going to be in okay now one thing I want to do here is show you how to clear the session so actually at the very top here when we go to the home page we're going to say session dot clear now the reason we're going to clear the session when the user goes to the home page is so that if they type in another room or another name or they try to navigate after going to the home page uh they can't ideally I don't want the user to be able to type in directly The Roots like slash room slash home I want them to go to the home page be directed to the chat room and then be able to leave the chat room and then join another chat room so it's just kind of good practice here when they go to the home page to clear the session which is going to delete anything that's inside of it and then we can go from there okay so last thing we're going to do here after we determine the room and the name is we are going to redirect the user to a new page which is going to be the chat room that they're joining so we're going to say return redirect and then URL underscore 4 and this is going to be for room now we haven't written this quite yet the room root but this is going to be the name of the function that we're redirecting to so notice we have redirect and what else do we have here sorry we don't have URL for so I need to import URL for but we have redirect and url4 which are two functions which we're using here and now we're going to Define another root which is app dot root this is going to be slash room and then we're going to say Define room and now we're going to return render template in the template we're going to render is room dot HTML perfect so that is what we have uh now so we're going to redirect to this root which will then render this room.html page which will then contain the chat room code and then we will essentially kind of join the user into the chat room and then start chatting so this is where we'll start getting into some of the socket code after we write the HTML for this room page and we kind of tested what we've currently done so before we go too much further let's test out what we currently have by re-running the server so we're going to go Python main.pi and we're going to go here to this root okay so let's open that up now I've got it open twice since the session is going to persist between different browser tabs I'm going to open up an incognito window just so that I can show you this with two different sessions because the Incognito session is going to be different than the typical session um hopefully that's clear but that's kind of how that that works and also session is another reason why for example when you like log into Facebook or you log into Instagram you go to a website you go to quite often you don't have to constantly like re-log in it's because your data is stored in a session a bunch of other data is stored there too just to make your experience a bit better okay so let's start by creating a room and then we'll see if we can join that room I know we're not really doing that yet but you'll kind of get a feel for how this input works so if I try to test out the errors if I click click create room you can see it renders the error you know please enter a name join a room same thing please enter a name if I do something like Tim and then I hit join a room it says please enter a room code but notice Tim is still here now same thing if I go with like hello and then I go create room please enter name but hello stays same with join room okay so let's create a room so I'm gonna go Tim and create room and then it redirects me to the room page nice now we don't know what the code was for this room so I actually can't join it which is what I was going to attempt to do you can see that at least what we've written so far uh is working so we'll deal with kind of that room code in a minute but for now I just want to add one kind of guard Clause here in our room root and make it so you can't go to slash room unless you've actually kind of done the registrations like you've entered your name or you've created a room or you've joined one from the home page so the way we're going to do that is we're going to say room is equal to session.get and we're going to get room and we're going to say if room is none or session dot get name uh is none or room is not in rooms then we're going to return redirect URL underscore 4 and then home now the reason I'm doing this is so that you can't just directly go to that slash room root it's only going to work if you first went to this page and you entered your name and you either generated a new room or you joined an existing room so that's why I'm doing all these checks here uh so you can't just directly go to this room page all right very good so now that we have the room page root kind of handle that we know how to navigate there we're gonna go to our room.html template and we're going to start writing kind of the basic code here I will have to write a bit of JavaScript code we're not going to do all of that this second for now I just want to get like a kind of chat window set up as you saw before and then once we have that we can kind of add all the socket coding so I know the socket stuff is coming later but we need to set all this stuff up stuff up first before the socket stuff actually makes sense so I'm going to type percent percent extends and then base dot HTML okay I'm then gonna go two percent and then block content then I'm gonna end my block super seven percent and block same thing as before we're going to put all of our code inside of here so we're going to create a div let's end the div to the class is going to be message Dash box we're then going to create a header so we're going to say H2 and I'm going to say chat room colon and then we're going to put as a variable that will enter into this template room now this is just so we know what the room code is so we could tell other people to join then we're going to have another div we're going to say class is equal to messages and I think that's fine for now actually we'll go with an idea as well as messages so we can access this from JavaScript and then I'm going to say slash diff now this is going to be an empty div but this is where we're going to inject all of our messages that we're getting from our socket server so we won't have the messages right away when we render the page but we'll insert them into this div next I'm going to create another div and this is going to be for our input so like for our actual message that we're sending so I'm going to say class is equal to inputs and inside of here I'm going to type input okay this is going to be type equal to text and this is going to be the message box where we're actually typing what we want to send right now I'm just going to say rows is equal to 3 just so we have some multi-line capability here for this input I'm going to say placeholder is equal to and then message and I'm going to say name is equal to message and then ID is equal to message okay so I know it's pretty repetitive but we need all of that and then we're going to create a button okay let's end our button and for our button it's going to be type equal to button although I don't know if we actually need to put that but I will for now the name is going to be send the ID is going to be the send BTN and then we're going to say on click is equal to and we're going to call a JavaScript function called send message which we'll write in a second and then we'll have the button say send okay so we are actually pretty much done the main content we need to have lastly I'm going to add a script tag here I'm going to say type is equal to Text slash JavaScript and I'm going to have another script tag now the reason I want this is so that the page updates without me having to refresh to do that I do need to use JavaScript and inside of here for now we're going to say VAR socket i o is equal to IO the reason we can call IO is because we have the CDN Library uh in our base.html okay so that's why we needed that and then we're going to have our function const send message is equal to an arrow function if you're not familiar with JavaScript this is a basic function this is just another way to create one these would be the parameters this is the body of the function and for now we'll just say console.log send okay we'll actually fill this in in a minute but for now I'm just kind of putting this boilerplate so that it doesn't give us an error with this send message function call okay fantastic so I think that's going to be good for now the next thing we need to do is do some styling first we can obviously have a look at uh well what this looks like so let's run our code let's go to this URL let's go Tim and create a room and there we go we get chat room now this is not what we want the chat room to look like but you can see we have our message box we have send we have the chat room header and then there is an empty div that you can't see which is our messages but I want to make that larger and have it look as uh it did in the uh demo so how are we going to do that well we're gonna go to style.css and we're going to fill in some of our styles so the first style we're going to do is message box this is the longest one but this is kind of the most stylistic aspect of our website obviously you can make this look better but I'll give you some basic styling so we're going to say border color is black we're going to say the Border width is two pixels I'm gonna say the Border style is solid we're going to say the Border radius is 10 pixels this gives us those kind of rounded Corners we're going to say the background color is equal to and I'll go with white smoke just slightly off-white color just so you get some contrast I'm going to give this a fixed height of 80 vertical height which is vertical height of the window then I'm going to go display Flex I'm going to go flex direction of column so we align all of our individual Flex items in a column I'm going to give this a fixed width of 80vw which is vertical width and then I'm going to say align items stretch so that all of our items will stretch to fill their parent so that they take up as much room as possible in terms of the width Direction okay fantastic now I'm going to say dot messages I'm going to say overflow Dash Y is scroll now this is that empty div right so if we look here we have this div messages and I want this to be a fixed height and to be scrollable like you would have in any kind of messaging app right you have the bottom part which is what you're actually sending your messages it's fixed or kind of glued to the screen whereas the scrolling part where all the messages are well you can scroll it so I need to kind of set that overflow y scroll means I can scroll through any overflow content that I have I'm going to say Flex one which means I'm going to take up a certain size of the screen here and I'm going to say with 100 percent okay lastly we're going to type dot inputs four dot inputs we're going to say padding is 10 pixel and then we're going to say display flex and this is the container that has our kind of message text box and actually excuse me here there's a few other things that we need to do that I haven't yet written so I'm going to do H2 and H4 because we're going to have an H4 header in a second uh actually are we gonna have an H4 no we're not we're just gonna have an H2 so we'll just do H2 I'm going to say text align Center so that goes in the center of the screen and then I'm going to go pound message which is the ID of our message box and I'm just going to say that this is flex one so that it will fill as much space as it can in its parent all right I think that's all we need I know I just wrote a lot of CSS there it is fairly basic CSS but that will give us some decent styling so let's reopen our window here and now let's go Tim create room and there you go we get our chat box window obviously you can make this look better if you want but I think this is good enough for now all right so now that we have all that let's go back to main.pi and let's start handling some of our socket stuff so really most of the kind of styling Pages root are finished we need to do all of our socket stuff now so the way that sockets kind of work is that when you go here to JavaScript and you initialize socket i o you're going to directly connect to the socket associated with the server that the kind of website is on so in this case we're going to connect to the socket server associated with our flask website which will be hosted on localhost so as soon as we connect there's an event that is emitted to our backend server called connect so the first thing we want to do is listen for that connection event and when that connection event occurs we want to put the user into the specific room uh that they're going to be in for the chat room application so there's all different kinds of stuff you can do here with flask sockets right you can send messages to everybody you can send message to one indiv
Original Description
Today, I will be showing you guys how to make a live chat application using Python, Flask & SocketIO! Please keep in mind, this tutorial is not for complete beginners, I recommend having some Python experience.
💻 Finished Code: https://github.com/techwithtim/Python-Live-Chat-App
💻 Flask Docs: https://flask-socketio.readthedocs.io/en/latest/getting_started.html
💻 Master Blockchain and Web 3.0 development today by using BlockchainExpert: https://algoexpert.io/blockchain - use code "tim" for a discount!
💻 ProgrammingExpert is the best platform to learn how to code and become a software engineer as fast as possible! https://programmingexpert.io/tim - use code "tim" for a discount!
⭐️ Timestamps ⭐️
00:00 | Introduction and Demo
02:03 | Setup/Installation
03:44 | Flask Initialization
09:09 | HTML Templates
15:48 | Home Page - Create/Join Room
24:27 | POST Request, Form Data, Sessions
40:51 | Chat Room
49:40 | Flask - Socket Connecting
56:22 | Flask - Socket Disconnecting
00:00 | JavaScript - Socket Connection
01:06:55 | Sending Messages
01:13:58 | Finishing Touches
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
👕 Merchandise: https://teespring.com/stores/tech-with-tim-merch-shop
📸 Instagram: https://www.instagram.com/tech_with_tim
📱 Twitter: https://twitter.com/TechWithTimm
⭐ Discord: https://discord.gg/twt
📝 LinkedIn: https://www.linkedin.com/in/tim-ruscica-82631b179/
🌎 Website: https://techwithtim.net
📂 GitHub: https://github.com/techwithtim
🔊 Podcast: https://anchor.fm/tech-with-tim
🎬 My YouTube Gear: https://www.techwithtim.net/gear/
💵 One-Time Donations: https://www.paypal.com/donate?hosted_button_id=CU9FV329ADNT8
💰 Patreon: https://www.patreon.com/techwithtim
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
⭐️ Tags ⭐️
- Tech With Tim
- Live Chat Room Tutorial
- Python
⭐️ Hashtags ⭐️
#techwithtim #Chatroom #pythontutorial
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Tech With Tim · Tech With Tim · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A* Path Finding Algorithm(Visualization)
Tech With Tim
Python Programming Tutorial #1 - Variables and Data Types
Tech With Tim
Python Programming Tutorial #2 - Basic Operators and Input
Tech With Tim
Python Programming Tutorial #3 - Conditions
Tech With Tim
Python Programming Tutorial #4 - IF/ELIF/ELSE
Tech With Tim
Python Programming Tutorial #5 - Chained Conditionals and Nested Statements
Tech With Tim
Python Programming Tutorial #6 - For Loops
Tech With Tim
Python Programming Tutorial #7 - While Loops
Tech With Tim
Python Programming Tutorial #8 - Lists and Tuples
Tech With Tim
Python Programming Tutorial #9 - Iteration by Item (For Loops Continued...)
Tech With Tim
Python Programming Tutorial #10 - String Methods
Tech With Tim
How to Overclock a NVIDIA GPU
Tech With Tim
Python Programming Tutorial #11 - Slice Operator
Tech With Tim
Python Programming Tutorial #12 - Functions
Tech With Tim
Python Programming Tutorial #13 - How to Read a Text File
Tech With Tim
Python Programming Tutorial #14 - Writing to a Text File
Tech With Tim
Python Programming Tutorial #15 - Using .count() and .find()
Tech With Tim
Python Programming Tutorial #16 - Introduction to Modular Programming
Tech With Tim
Python Programming Tutorial #17 - Optional Parameters
Tech With Tim
Python Programming Tutorial #18 - Try and Except (Python Error Handling)
Tech With Tim
Python Programming Tutorial #19 - Global vs Local Variables
Tech With Tim
Python Programming Tutorial #20 - Classes and Objects
Tech With Tim
Cool VBS Script to Prank Your Friends!
Tech With Tim
How to Overclock an AMD GPU
Tech With Tim
Best GPU'S For Mining Ethereum (2018)
Tech With Tim
Recursion and Memoization Tutorial Python
Tech With Tim
Ethereum Mining Rig - Hardware Guide
Tech With Tim
Pygame Tutorial #1 - Basic Movement and Key Presses
Tech With Tim
How to Install Pygame (Windows 8/10)
Tech With Tim
How to Trade Your Cryptocurrency (Bitcoin, Ethereum etc.) For Cash!
Tech With Tim
How to Mine Ethereum 2018 - WORKING (Super-Easy)
Tech With Tim
Microphone Comparison - $10 Mic vs $150 Mic (Blue Yeti USB)
Tech With Tim
Pygame Tutorial #2 - Jumping and Boundaries
Tech With Tim
Pygame Tutorial #3 - Character Animation & Sprites
Tech With Tim
Pygame Tutorial #4 - Optimization & OOP
Tech With Tim
OBS Studio Tutorial - Best OBS Settings
Tech With Tim
Linear Search Algorithm - Python Example and Code
Tech With Tim
Make Any Mic Sound AMAZING! (WITH OBS)
Tech With Tim
Binary Search Algorithm - Python Example & Code
Tech With Tim
Pygame Tutorial #5 - Projectiles
Tech With Tim
Pygame Game - Mini Golf
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 1)
Tech With Tim
Pygame Tutorial - Projectile Motion (Part 2)
Tech With Tim
Pygame Tutorial #6 - Enemies
Tech With Tim
Pygame Tutorial #7 - Collision and Hit Boxes
Tech With Tim
Pygame Tutorial #8 - Scoring and Health Bars
Tech With Tim
Cloud Mining vs. Hardware Mining - 2018
Tech With Tim
How to Install Pygame on Mac OSX (Fast-Simple)
Tech With Tim
Pygame Tutorial #9 - Sound Effects, Music & More Collision
Tech With Tim
Pygame Tutorial #10 - Finishing Touches & Next Steps
Tech With Tim
How to Fade Your Screen in Pygame [CODE IN DESCRIPTION]
Tech With Tim
How to Create a Button in Pygame [CODE IN DESCRIPTION]
Tech With Tim
Pygame Side-Scroller Tutorial #1 - Scrolling Background/Character Movement
Tech With Tim
Pygame Side-Scroller Tutorial #2 - Random Object Generation
Tech With Tim
Pygame Side-Scroller Tutorial #3 - Collision
Tech With Tim
Pygame Side-Scroller Tutorial #4 - Scoring and End Screen
Tech With Tim
How to Create A Message Box in Python - Tkinter
Tech With Tim
Is Ethereum Mining Still Profitable - Is It Worth It (April 2018)
Tech With Tim
How to Run MAC OSX on a WINDOWS PC (Clover Boot-loader)
Tech With Tim
Programming Problem #1 - Alphabet Soup (Beginner/Novice)
Tech With Tim
More on: Tool Use & Function Calling
View skill →Related Reads
📰
📰
📰
📰
I built a native Android app in an afternoon, and I've never written a line of Kotlin
Dev.to · Tilde A. Thurium
Vibe Coding Is Real Now — Here’s How to Do It Without Wrecking Your Codebase
Medium · Programming
How to build your first MCP server in 10 minutes
Dev.to · GrahamduesCN
Revisiting My Software Engineering Journey
Medium · JavaScript
Chapters (12)
| Introduction and Demo
2:03
| Setup/Installation
3:44
| Flask Initialization
9:09
| HTML Templates
15:48
| Home Page - Create/Join Room
24:27
| POST Request, Form Data, Sessions
40:51
| Chat Room
49:40
| Flask - Socket Connecting
56:22
| Flask - Socket Disconnecting
| JavaScript - Socket Connection
1:06:55
| Sending Messages
1:13:58
| Finishing Touches
🎓
Tutor Explanation
DeepCamp AI