Working with Client-Side Session in Flask
hello and welcome in this post I will discuss how to work with sessions in the flask framework, in some cases, we need to save login sessions from our users because we don’t want the user to have to log in when opening the website,
so we need to save the login session, in flask we can use session
Creating New Session
to create a new session we need to create a new route for example
@app.route("/set_email", methods=["GET", "POST"])def set_email():if request.method == "POST": # save session session["email"] = request.form["email_address"]return render_template("set_email.html")
and create a new form to retrieve data from users
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Set Email</title><link rel="stylesheet" href="{{ url_for('static', filename='bulma.min.css') }}"></head><body><div class="field"><form class="control has-icons-left has-icons-right" method="POST"><label class="label" for="email">Enter your email address:</label><input class="input" type="email" id="email" name="email_address" required /><button class="button is-success" type="submit">Submit</button></form></body></html>
now you can see the result and
Get Session Data
after creating and setting the session we need to get the session that we just made, for that create a new route to getting the session
# get session email@app.route("/get_email")def get_email():return render_template("get_email.html")
and create the template
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{{ session['email'] }}</title></head><body>{% if session['email'] %} <h1>Welcome {{ session['email'] }}!</h1>{% else %} <h1>Welcome! Please enter your email <a href="{{ url_for('set_email') }}">here.</a></h1>{% endif %}</body></html>
now we successfully get the session but there are some drawbacks, for example, if we open the website in the incognito window, the session we saved previously doesn’t exist or is lost.
Delete Session Data
now we need to handle if user logout, so we remove the session, to remove create a new route
# delete session email@app.route("/delete_email")def delete_email(): # Clear the email stored in the session object session.pop("email", default=None) return "<h1>Session deleted!</h1>"
now the session has been deleted
Conclusion
By using the session we can easily store login information, so the user does not need to log in repeatedly