What Are Sessions in Web Development?
Hello everyone and welcome back to our Flask tutorial. So in today's video, what I'm going to be doing is talking about sessions. Now to try to explain to you guys what sessions are, I'm going to give you an example of what we did in the previous video and talk about a way in which we could do this better. So essentially we had this login page and once we logged in, we got the user's name and then we redirected them to a page that showed them their name, just pretty much popped that up on the screen.
Now this is great, that's fine, but every time that we want to see the user's name we need to log in again and again and again. And if we ever want to keep seeing the user's name, we need to continue to log in. Now what if we want to redirect to another page and that page wants the user's name as well? Well, that means we have to set up a way to pass to that page the user's name. We've got to use a parameter, we have to set up this link. It's just really not the best way to do things and sometimes, you know, you don't want to redirect to a page that says /Tim or /Joe or /Bill.
So what we're going to do to actually pass around information through our, you know, backend here and through our different web pages is use something called sessions. Now sessions are great because they're temporary, they're stored on the web server, and they're just simply there for quick access of information between all the different pages of your website. Think of a session as something that you're going to load in, you're going to use while the user is on your website. So while they're browsing on the website, and then as soon as they leave, it's going to disappear.
So essentially if we're doing an example, let's say, you know, of Instagram or Facebook, when someone logs in, there's going to be a new session created. It's going to store their username, probably some other information as well about what they're doing on the website at the current time. And then as they can go between different pages, those pages can access that session data. So it can say, okay, so I moved to, you know, my profile page, this is the profile of Tim. I know that because I stored that in a session. So let's show all this different information that I have stored in the session as well or whatever it is, right? And then as soon as that user leaves the webpage or logs out of the webpage, all of that session data is erased, it disappears. And the next time they log in, that session data will be reloaded into the session where it can be used for the rest of the pages.
Now this is very useful. I'm going to show you guys kind of how this works. It should start to make a bit more sense. But that is kind of the basics of sessions. Just remember they're temporary, they're stored on the server—they're actually not stored on the client side—and they're kind of designed for just quick access of information and a way to pass stuff around our server.
Storing & Retrieving Session Data in Flask
Okay, so what I want to do essentially is I want to do an example where the user logs in, we create a session for them that stores the name, and then we can redirect to another page that doesn't have this, you know, /user. So I'm actually just going to get rid of this and make this /user here. We don't have any parameters here, and we can still access that person's name and display that on the screen. So let's start with that.
What we need to do is actually start by importing session here. I'm going to show you how easy this is to actually do. So what we can do is inside request.post, so when the user presses login or submit or whatever on that login page, what we're going to do is set up some session data based on whatever information they typed in. So I'm going to say session and in this case user equals user. And this is actually as easy as it is to set up some data for our session.
So this session stores data as a dictionary just like we've seen this requests.form working. So if I want to create a new, you know, piece of information in my session, what I can do is simply type session, the name of whatever I want that dictionary key to be, and then set it equal to some specific value. In this case, this is the user that clicked submit and you know, submitted their name to this form. So that's it. That's literally how we store information in the session.
Now, how do we get that information? So what I want to do is I'm going to change this redirect here to redirect to user, but I'm not going to pass the user as an argument. I'm actually just going to redirect, I'm not going to pass any information, and from this user function, I'm going to get the session information. Now the way that I do this is I first check if there's any information in the session. So I want to make sure that before I reference that dictionary key that we've actually, you know, logged in, because technically someone could just type /user and access this page without being logged in, right? So what I'm going to do is say if user, which is the name of that session key, in session, then what I'll do is return an F string. And I'm actually going to get this user, so I set user = session['user'] and we know this is valid because we just checked if user was in session, and then I'll simply display the user like that and put this inside the brackets so it shows up. So that is as easy as it is to store and retrieve session data.
Just remember all you do is literally make a dictionary key, put it inside session. I've imported session up here. Set it equal to a value, and then you can access it after you've checked if it exists. Now, what I'm going to do if this session does not exist, so if there's no user in my session, that means that I haven't logged in yet, or I've left the browser and I need to log in again. So what I'm going to do is actually redirect back to the login page and say, hey, you need to log in or whatever it is. So I'm just going to say return redirect(url_for('login')). And then since we have a get method when we're returning over here, we will return this render_template for login.html. They can hit submit and they can redirect back to the user page. So let's start with that and then we'll get into some other more complicated things. So to run this I'm just going to go python tutorial5.py.
Okay, so let's go copy this link here and we'll head to the /login page and see what we get. Okay, so this is our homepage. So sorry, /login. Let's try Tim. If I hit submit, and if I hit submit, we get an error.
The Secret Key and a Working Example
Because I just remembered that I need to add something to my file here. So essentially all of this session data that we store is actually encrypted on the server, and that means we actually need to define something called a secret key, which will be the way that we decrypt and encrypt this data. So to do that, I'm going to type at the beginning of my program app.secret_key = and then you can literally just type any string in here that you want. I mean it would be wise to make this something somewhat complicated, but I'm just going to make mine hello as my secret key. But we do just need to set a secret key. I completely forgot that that was actually a necessary step in doing this.
Okay, so let me refresh this page now and see what we get. Actually I've got to go back to /login. So let's go to /login. This hopefully should be good now. I'm going to type Tim, hit submit, and then you can see we're redirected to a page that says Tim. And notice again, right, that I don't pass any information to here about the user. We're getting it from this session variable.
So let's go back and let's do something else now. So if I close this browser and I open it back up and I go to whatever that link is and then I go to /user, you'll see that it redirects me back to logging in. Well, why does it do that? Because when I close the web browser, my session data is actually deleted from the server, which means that if I want to go back to the user page, I need to create a new session and log in again. In this case, we'll log in with Joe and we see we are redirected to Joe. I can go, you know, to /home and that will... /home isn't a page, but if I go to / and then I go back to /user, you'll see that it brings me back to Joe because it's stored that information in the session. So again, very useful. That is how that works.
Logging Out and Clearing the Session
Now it's talking about actually clearing a session and logging out. So we'll leave that up for now, but what I want to do is actually create a logout page and show you how you can manually clear session data. Because essentially if someone logs out, you probably want to delete all the information associated with their session, or at least some of that information. So what I'm going to do is set up a new function here. So a new page, we'll just call this one /logout like that.
Let's define logout and all we're going to do in here is actually remove some data from our session. What I'm going to do is say session.pop('user', None). Now what this is going to do is actually remove the user data from my sessions. This is just how you remove it from the dictionary. And then this None is just a message that's associated with removing that data. I'm not really going to talk about that because I don't fully understand why we have None here, but anyways, it's not that important. So once we log out, we will actually return a redirect to the login page. So we'll say url_for in this case login. Okay, awesome.
Now what I want to do is add one more thing to the /login route. Essentially, I check if, when we redirect to login here, if we're already logged in, I just redirect us to the user page. Otherwise, I'm going to actually redirect us to this login.html form. So to do that is pretty easy. All I'm going to say is if 'user' in session, which essentially means, you know, we've signed in, then all I need to do is return a redirect to the url_for in this case user. And that is as easy as it is. So essentially what I've done here is set up a way that we can log in using a session, and then we can be redirected to a specific page without sending that information directly to it through a parameter. We can display that information. We can log out now by popping that session data. And then if we go to the login page and we're already logged in, it's actually going to redirect us to this user page and just show us that information. So let's do that now.
Um, if I go to /logout, you can see that it redirects us to the login page. And now if I were to try to go to back to /user, we get redirected immediately back to the login page because we're not signed in yet. So if we sign in with say Tim, there we go, we're on the user page. And now if I go to /login, you can see it actually just redirects us back to this same page because we're already logged in. And then again, we can log out, brings us to the login page, and if I go to /user, that's not going to work. And that is kind of how we do that.
Making Sessions Permanent
Now remember that this session data is actually deleted when I close my browser. So I'm gonna show you quickly a way that we can store our session data for longer, because what actually happens is this session data is stored in a temporary directory on the server, and we can set how long we want that information to be stored for by using something called permanent sessions.
Now, what I'm going to do to set up the permanent session here is define first of all how long I want a permanent session to last. So you may have noticed sometimes, you know, you revisit a website a few days later and you just log in immediately. You don't actually have to, you know, go through the process, or maybe your information's already typed in and you just hit login. Some of this information is stored in permanent sessions, which means it's storing it for longer than, you know, however long you're in the web browser. So that every time you go back to that webpage you can quickly access information that you need and you don't need to log back in.
So what I'm going to do is actually just import something here. So I'm going to say from datetime import timedelta. Now the reason I'm doing this is because I want to set up the max time that our session could last for. And the way that I do that is app.permanent_session_lifetime like that, and then it's going to be equal to timedelta. And then you can say days= and how many days you want this to actually last for. Let me make sure this is correct. So I could say days and I could say five days. And if I do this, what this means is we're going to store our permanent session data for five days. I can also do something like minutes=5. And if I do that, that means we're going to store our permanent session data for five minutes and then delete it after that.
Now, how do we make a session permanent? Well, this is actually pretty easy. All we're going to do is when we log in and we actually have, we've got this information, we've logged in, everything's valid, say we've checked this against the database, then we can make the session permanent by saying session.permanent if I could spell this correctly = True. I don't know why that was such a struggle. Okay, so session.permanent = True. And now this is going to define this specific session as a permanent session, which means it's going to last as long as we've defined up here. By default if you don't do this, it sets our session to not permanent, so false here, and that means it's going to last for as long as you're actually on the web page, or sorry, in your browser.
So let's see if this is working now. I believe it is. So let's go back to that web page. Um, give it a second here. What's our error? I guess I gotta hit enter in the command prompt. Okay, so let's go /login. Let's do our name, so Tim, and then let's actually close this and let's go back to it. So, paste that in here. Why is this not working? Okay, and then we'll go to /login and you can see we are redirected back to this user page because our session data was actually saved permanently. So when I actually closed this window, it didn't do anything.
So now let's say logout. We've logged out and then obviously now our session data has been removed because we had this session being removed from the logout.
Conclusion and Best Practices
So that is kind of everything about sessions. There's obviously some more stuff that you guys can do with this, but this is the basics. And just remember, sessions are something that you're using temporarily. You should never be storing permanent data in a session. And typically what ends up happening is you'll log in, you'll validate some stuff with the database, you'll actually grab some information from the database and store that in a session, and then whenever you log out, you'll remove that information. And when you log in again, you can load it back in. So this is information that you don't really care about but it's just there for quick retrieval and for easy access from different web pages so you don't have to continually read from the database. And you also just know some of this information passing between the pages, you don't have to send them through, you know, the URL, which is not a secure way to send information.
So that has been it for this video. If you guys enjoyed, make sure you leave a like and subscribe and I will see you guys in another one.