- examples/big-suite: E-Commerce 10 functions, 6 layers, real depends_on - provider: nodejs packages now wrapped in ESM zip (buildJSDeployZip) - provider: loadPackageLiteral reads raw file, nodejs zip via source_dir - all 10 functions verified working: python/node/ruby/go runtimes
71 lines
2.4 KiB
Python
71 lines
2.4 KiB
Python
import json
|
|
import time
|
|
from flask import request
|
|
|
|
# In-memory корзина (живёт пока жив под poolmgr)
|
|
_CARTS: dict = {}
|
|
|
|
|
|
def _get_cart(user_id: str) -> dict:
|
|
if user_id not in _CARTS:
|
|
_CARTS[user_id] = {"user_id": user_id, "items": [], "created_at": int(time.time())}
|
|
return _CARTS[user_id]
|
|
|
|
|
|
def _cart_total(cart: dict) -> float:
|
|
return round(sum(i["price"] * i["qty"] for i in cart["items"]), 2)
|
|
|
|
|
|
def main():
|
|
method = request.method.upper()
|
|
user_id = request.headers.get("x-user-id", "user-1")
|
|
body = {}
|
|
if request.data:
|
|
try:
|
|
body = json.loads(request.data)
|
|
except Exception:
|
|
pass
|
|
|
|
cart = _get_cart(user_id)
|
|
|
|
if method == "GET":
|
|
return json.dumps({
|
|
"status": "ok",
|
|
"cart": cart,
|
|
"total": _cart_total(cart),
|
|
"item_count": len(cart["items"]),
|
|
})
|
|
|
|
if method == "POST":
|
|
# Добавить товар: {"product_id": "p-001", "name": "...", "price": 29.99, "qty": 2}
|
|
required = ["product_id", "name", "price", "qty"]
|
|
if not all(k in body for k in required):
|
|
return {"status": 400,
|
|
"body": json.dumps({"error": "missing fields", "required": required}),
|
|
"headers": {"Content-Type": "application/json"}}
|
|
|
|
# Если товар уже в корзине — увеличиваем qty
|
|
for item in cart["items"]:
|
|
if item["product_id"] == body["product_id"]:
|
|
item["qty"] += int(body["qty"])
|
|
return json.dumps({"status": "ok", "action": "updated", "cart": cart,
|
|
"total": _cart_total(cart)})
|
|
|
|
cart["items"].append({
|
|
"product_id": body["product_id"],
|
|
"name": body["name"],
|
|
"price": float(body["price"]),
|
|
"qty": int(body["qty"]),
|
|
})
|
|
return json.dumps({"status": "ok", "action": "added", "cart": cart,
|
|
"total": _cart_total(cart)})
|
|
|
|
if method == "DELETE":
|
|
product_id = body.get("product_id", "")
|
|
cart["items"] = [i for i in cart["items"] if i["product_id"] != product_id]
|
|
return json.dumps({"status": "ok", "action": "removed", "cart": cart,
|
|
"total": _cart_total(cart)})
|
|
|
|
return {"status": 405, "body": json.dumps({"error": "method not allowed"}),
|
|
"headers": {"Content-Type": "application/json"}}
|