This is specific to the flask_session library only
SESSION_PERMANENT = False – So this session has a default time limit of some number of minutes or hours or days after which it will expire.
SESSION_TYPE = “filesystem” – It will store in the hard drive (these files are stored under a /flask_session folder in your config directory.) or any online ide account, and it is an alternative to using a Database or something else like that.
Python3
app =Flask(__name__)
app.config["SESSION_PERMANENT"] =False
app.config["SESSION_TYPE"] ="filesystem"
Session(app)
Remember User After Login
So we will start making two basic pagesand their route called index.html and login.html
login.html contains a form in which the user can fill their name and submit
index.html is the main page
Python3
@app.route("/")
defindex():
returnrender_template('index.html')
@app.route("/login", methods=["POST", "GET"])
deflogin():
returnrender_template("login.html")
We need to record the username in the session when they submit the form
And we are using a dictionary in python where “name” is the key = request.form.get(“name”) is a value
Python3
@app.route("/login", methods=["POST", "GET"])
deflogin():
# if form is submited
ifrequest.method =="POST":
# record the user name
session["name"] =request.form.get("name")
# redirect to the main page
returnredirect("/")
returnrender_template("login.html")
After storing the user name we need to check whenever user lands on the index page that any session with that user name exists or not.
If the user name doesn’t exist then redirect to the login page.
Python3
@app.route("/")
defindex():
# check if the users exist or not
ifnotsession.get("name"):
# if not there in the session then redirect to the login page
returnredirect("/login")
returnrender_template('index.html')
After successfully remember the user we also need a way to logout the users.
So whenever the user clicks logout change the user value to none and redirect them to the index page.