from flask import Flask from flask import request from flask import session from flask import request import secrets counter = Flask(__name__) counter.secret_key = secrets.token_bytes() # Generate the page. def generate(loggedin, count): # Text tweaking notornot = "" if loggedin else " not" buttxt = "LOGOUT" if loggedin else "LOGIN" return f""" Flask Sessions

Hello, Flask 2

This script passes state using a Flask session.

The current count is {count}. You are{notornot} logged in.

""" # Come at the app without a form, you're new. Expect to have lost # your mind. (May or not be ideal) @counter.route("/",methods=['GET']) def init(): # Initialize the state. loggedin = session['loggedin'] = False count = session['count'] = 1 return generate(loggedin, count) @counter.route("/",methods=['POST']) def count(): # Get the original logged in value. (This example doesn't make it # hard to log in, but if we were more realistic, we'd still believe # the contents of the session.) loggedin = session['loggedin'] # Apply login request. if 'LOGIN' in request.form: loggedin = session['loggedin'] = True if 'LOGOUT' in request.form: loggedin = session['loggedin'] = False # Increment the count. session['count'] += 1 return generate(loggedin, session['count'])