Skip to content

Instantly share code, notes, and snippets.

@bchaber
Created October 21, 2021 10:14
Show Gist options
  • Save bchaber/24986d679495a90364f922ff152b4daf to your computer and use it in GitHub Desktop.
Save bchaber/24986d679495a90364f922ff152b4daf to your computer and use it in GitHub Desktop.
A simple web application with a server-side application state (session ID)
from flask import Flask
from flask import request
from flask import make_response
from json import loads, dumps
import random, string
app = Flask(__name__)
carts = { # server-side application state
'deadbeef' : {'Marchewka' : 4}
}
@app.route("/add2cart", methods=["POST"])
def add2cart():
sessionid = ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
cookies = request.headers.get("Cookie", "")
# try to read the session ID from a cookie
for cookie in cookies.split(";"):
if cookie.startswith("sessionid="):
sessionid = cookie[len("sessionid="):]
# if the user has no cart -- create an empty one
if sessionid not in carts:
carts[sessionid] = {}
product = request.form.get("product", "")
if product.strip() == "": # strip removes leading and trailing whitespaces
response = make_response("Pusta nazwa produktu", 400)
return response # exit early with an error code
print(f"Dodaje {product} do {carts[sessionid]} ({sessionid})")
if product in carts[sessionid]:
carts[sessionid][product] += 1 # increase
else:
carts[sessionid][product] = 1 # initialize
response = make_response("OK", 200)
# return a session ID, especially if the request had no session cookie
response.headers["Set-Cookie"] = "sessionid=" + sessionid + "; HttpOnly"
return response
@app.route("/")
def index():
html = """
<!doctype html>
<html>
<body>
<form action="/add2cart" method="POST">
<input type="text" name="product" placeholder="Nazwa produktu" />
<input type="submit" value="Dodaj jedną sztukę do koszyka" />
</form>
<p>W naszym warzywniaku mamy</p>
<ul>
<li>Marchewka;</li>
<li>Rzodkiewka;</li>
<li>Ogórek;</li>
<li>Kalarepka.</li>
</ul>
"""
response = make_response(html, 200)
return response
# $ python3 -m pip install gunicorn
# $ gunicorn -w 1 app:app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment