Record#
- Today's study is about HTTP & SESSION. Session is a storage method that stores some user-related content on the user's computer.
- Before storing the session, you need to establish a session key. This key must not be leaked, otherwise the user's information will not be secure. So the key should be stored in the environment variable.
app.secret_key = os.environ['sessionKey']
- When you need to store, just assign the session data. For example:
session["myName"]
- Use
session.get("myName")
to determine if the variable exists. - Use
session.clear()
to clear all sessions. - Today's exercise is to add the functionality of caching the username and logging out based on yesterday's exercise.
- In today's exercise, I also learned a new knowledge point. Two routes with the same name can exist in the route setting, but the methods behind them cannot be the same. Just like the login route in the code.
CODE#
from flask import Flask, request, redirect, session
from replit import db
import os
app = Flask(__name__, static_url_path='/static')
app.secret_key = os.environ['secret_key']
@app.route("/")
def index():
if session.get("name"):
return redirect("/login")
else:
page = """
<p><a href="/sign">Sign Up</a></p>
<p><a href="/log">Log In</a></p>
"""
return page
@app.route("/sign")
def sign():
if session.get("name"):
return redirect("/login")
else:
f = open("sign.html", "r")
page = f.read()
f.close
return page
@app.route("/signup", methods=["POST"])
def signup():
if session.get("name"):
return redirect("/login")
else:
user = request.form
if user["username"] not in db.keys():
db[user["username"]] = {
"username": user["username"],
"name": user["name"],
"password": user["password"]
}
session["name"] = user['name']
page = f"Hello {session['name']}"
else:
page = f"{user['username']} exists"
return page
@app.route("/log")
def log():
if session.get("name"):
return redirect("/login")
else:
f = open("login.html", "r")
page = f.read()
f.close
return page
@app.route("/login", methods=["GET"])
def sessionlogin():
if session.get("name"):
page = f"<h1>Hello {session['name']}</h1><p><a href='/reset'>Reset</a></p>"
return page
@app.route("/login", methods=["POST"])
def login():
user = request.form
if db[user["username"]]["username"] == user["username"] and db[
user["username"]]["password"] == user["password"]:
session["name"] = db[user["username"]]["name"] # Store the user's name in the session
return redirect("/login")
else:
page = "Username Or Password error"
return page
@app.route("/reset")
def reset():
session.clear()
return redirect("/log")
app.run(host='0.0.0.0', port=81)