Flask Sessions

Session: a dictionary object containing session variables and associated values stored on server.
it's a time interval from login until logout

Session ID: stored in top of cookie
secret_key: to encrypt the session id
session.pop(): to cancel a session id


vi templates/sessionlogin.html

<form action = "" method = "POST">
  <p><input type = "text" name = "username"/></p>
  <p<<input type = "submit" value = "Login"/></p>

vi session.py
from flask import Flask, session, redirect, url_for, escape, request, render_template
ap = Flask(__name__)


def sessions():
   if 'username' in session:
      username = session['username']
      return 'Logged in as ' + username + '<br>' + \
         "<b><a href = '/logout'>click here to log out</a></b>"
   return "You are not logged in <br><a href = '/login'></b>" + \
      "click here to log in</b></a>"

@ap.route('/login', methods = ['GET', 'POST'])
def login():
   if request.method == 'POST':
      session['username'] = request.form['username']
      return redirect(url_for('sessions'))
def logout():
   # remove the username from the session if it is there
   session.pop('username', None)
   return redirect(url_for('sessions'))

ap.secret_key = '<input any string>'

if __name__ == '__main__':
   ap.run(host= '')

python session.py

#open http://<ip/url>:5000/sessions


Common Flask Errors And Their Solutions:

Leave comments


Copyright(c) 2017 - PythonBlogs.com
By using this website, you signify your acceptance of Terms and Conditions and Privacy Policy
All rights reserved