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

example:

vi templates/sessionlogin.html

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


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


@ap.route('/sessions')

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'))
   return
render_template("sessionlogin.html")
     
@ap.route('/logout')
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= '0.0.0.0')

python session.py

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

==

Common Flask Errors And Their Solutions:
https://www.jjude.com/flask-errors/



Leave comments

authimage

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