0% found this document useful (0 votes)
2 views

Lab6_Session_Variables

The document outlines the use of session data in Flask, explaining how it allows for temporary data storage during a user's session on a web application. It provides examples of managing session variables, redirecting users, and creating a login page with user authentication. Additionally, it includes activities for extending functionality based on user roles and emphasizes common mistakes and tips for working with Flask.

Uploaded by

ictsupport
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lab6_Session_Variables

The document outlines the use of session data in Flask, explaining how it allows for temporary data storage during a user's session on a web application. It provides examples of managing session variables, redirecting users, and creating a login page with user authentication. Additionally, it includes activities for extending functionality based on user roles and emphasizes common mistakes and tips for working with Flask.

Uploaded by

ictsupport
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lab 6: Session Data in Flask

GW CS 2541W: Database Systems and Team Projects - 2024


Prof. Gabe Parmer, Sameen Ahmad, Kate Halushka, and Dania Abdalla

1
Has this ever
happened to you?

Why do you think we


need this feature?
2
Session Data

● “Session” refers to the time between a client logging in to the server and logging
out of the server
● With Flask, Session data is stored in the client’s browser on top of cookies
● Each client has their own session that is assigned a Session ID
● Use Cases
○ Remember a user when they log in
○ Store items in a cart while shopping online
● Sessions last for 31 days unless SESSION_PERMANENT is set to false (in which
case they last until the browser or tab is closed)

3
Using Session with Flask
● The Session object is a dictionary object with key-value pairs of session variables and associated
values
● For session data to be encrypted, also set a SECRET_KEY

To set a ‘username’ session variable: To release a session variable:

session[‘username’] = “admin” session.pop(‘username’, None)

To set the session secret key: To clear all session variables:

app.secret_key = “any string” session.clear()

4
Redirecting in Flask

from flask import Flask, redirect, url_for, session ● The redirect() function allows us to redirect
app = Flask(‘app’) users to a URL that we specify
● Instead of specifying a URL, we can also
redirect to a function using url_for()
@app.route(‘/’)
● For example, the following lines would be
def login():
equivalent for our code example:
...

@app.route(‘/logout’)
redirect(‘/’)
def logout():
session.clear()
return redirect(‘/’)
redirect(url_for(‘login’))
app.run(host=’0.0.0.0’, port=8080)

5
Session Example
We can access our
from flask import Flask, session, redirect home.html session variables in
app = Flask(‘app’) templates, too!
app.secret_key = “secret”
<html>
Why do we check the
... <body>
session to make sure a
<h1> Welcome, {{ session[‘name’] }} </h1
@app.route(‘/home’) user is logged in?
def home(): </body>

if ‘name’ in session: </html>

return render_template(“home.html”)
return redirect(‘/’)

app.run(host=’0.0.0.0’, port=8080)

6
Session Refresher
● Session data allows us to temporarily store data that we want to preserve across
different pages (i.e. a logged in user or a shopping cart of products)

Setting session variables: Checking if a session variable is set:

session[‘username’] = “admin” if ‘username’ in session:

Clearing session variables: Using session variables in templates:

session.pop(‘username’)
<p> Hello, {{ session[‘username’] }} </p>
session.clear()

7
Refresher: Form Data

from flask import Flask, render_template, request


app = Flask(‘app’) <body>
<form action="/" method="POST">

@app.route(‘/’, methods=[‘GET’, ‘POST’]) <input type="text" name="username">

def get_username(): <input type="submit" name="submit">


if request.method == ‘POST’: </form>
uname = request.form[“username”] </body>
return render_template(‘simple_form.html’)
app.run(host=’0.0.0.0’, port=8080)

8
Common Mistakes & Tips!

1. You must set up your database connection and create a cursor object within each
function in your Flask app
2. If you are getting a Python indentation / tab error but everything looks aligned on
your screen, this is likely due to a collaboration lag in Repl. Have every group
member check the spacing on their own screen and adjust!
3. If you want styling tips or aren’t sure about syntax for HTML / CSS,
w3schools.com is a great resource!
4. If you need to reset your database, run the following command in the Shell:

sqlite3 <db file name> “.read <sql file name>”

9
Activity 1: Login Page

1. Create a login page (login.html) that takes a username and password, verifies the
user is in the database, and signs them in
○ Display an error message on the login page if authentication fails
2. Upon successful login, the user should be redirected to a homepage (home.html)
that displays “Welcome, <NAME> ” at the top (using session variables!)
○ Add a Sign Out button on the homepage that clears the session and redirects the user back to the
login page
○ Users should not be able to access the home page if not signed in

10
Activity 2: User Login

1. Extend Activity 1 so that when a username and password are determined to be in


the database, also store the type of user in a session variable (The three user roles
are: Student, TA, and Professor)
2. When signed in, the home page (home.html) should display different things based
on the type of user stored in the session
○ Students can view the student roster (name, ID, and email of all students)
○ TAs can view the student roster and engagement points
○ Professors can view the student roster, engagement points, and grades

11

You might also like