Created
October 19, 2021 09:56
-
-
Save bchaber/f554185fc24ffe8c4c261a1a431cc2eb to your computer and use it in GitHub Desktop.
A simple web application with application state on the client side (in a cookie)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
from flask import request | |
from flask import make_response | |
from json import loads, dumps | |
app = Flask(__name__) | |
@app.route("/add2cart", methods=["POST"]) | |
def add2cart(): | |
cart = {} # default value, can be loaded from cookies | |
cookies = request.headers.get("Cookie", "") | |
for cookie in cookies.split(";"): # foo=1; cart={}; bar=true; baz=abc | |
if cookie.startswith("cart="): | |
cart = loads(cookie[len("cart="):]) # assume that it is JSON | |
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 {cart}") | |
if product in cart: | |
cart[product] += 1 # increase | |
else: | |
cart[product] = 1 # initialize | |
response = make_response("OK", 200) | |
response.headers["Set-Cookie"] = "cart=" + dumps(cart) + "; 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 flask | |
# $ python3 app.py | |
app.run() # go to http://127.0.0.1:5000/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment