[
run]
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"""
<html>
<head>
<meta charset="utf-8">
<title>Flask Sessions</title>
<link rel="stylesheet" href="/static/genstyle.css" type="text/css">
<style>
p, form * {{ text-align: center; }}
</style>
</head>
<body>
<h1>Hello, Flask 2</h1>
<p>This script passes state using a Flask session.</p>
<form method="post">
<p>The current count is {count}. You are{notornot} logged in.</p>
<div><input type="submit" name="{buttxt}" value="{buttxt}">
<input type="submit" name="next" value="next"></div>
</form>
</body>
</html>"""
# 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'])