April 14th, 2017

Flask Request Object III – sessions

others, Programing, Python, by admin.

Session – a dictionary object containing session variables and associated values.


vi session.py

from flask import Flask, session, redirect, url_for, escape, request
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’))
return ”’

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


def logout():
# remove the username from the session if it is there
session.pop(‘username’, None)
return redirect(url_for(‘sessions’))

ap.secret_key = ‘<any random string>’

if __name__ == ‘__main__’:
ap.run(host= ‘’)



Back Top

Leave a Reply