Skip to content
This repository was archived by the owner on Jul 11, 2025. It is now read-only.

Improve checkout process and error handling #37

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 26 additions & 15 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import copy
from flask import Flask, request, json, abort
from flask_cors import CORS

Expand Down Expand Up @@ -37,14 +38,18 @@ def unhandled_exception():

def process_order(cart):
global Inventory
tempInventory = Inventory
temp_inventory = copy.deepcopy(Inventory)
for item in cart:
if Inventory[item['id']] <= 0:
raise Exception("Not enough inventory for " + item['id'])
else:
tempInventory[item['id']] -= 1
print 'Success: ' + item['id'] + ' was purchased, remaining stock is ' + str(tempInventory[item['id']])
Inventory = tempInventory
item_id = item.get('id')
if not item_id:
raise ValueError("Cart item is missing an 'id'")
if item_id not in temp_inventory:
raise ValueError(f"Item '{item_id}' not found in inventory.")
if temp_inventory[item_id] <= 0:
raise ValueError(f"Not enough inventory for {item_id}")
temp_inventory[item_id] -= 1
print(f"Success: {item_id} was purchased, remaining stock is {temp_inventory[item_id]}")
Inventory = temp_inventory

@app.before_request
def sentry_event_context():
Expand All @@ -65,11 +70,17 @@ def sentry_event_context():

@app.route('/checkout', methods=['POST'])
def checkout():

order = json.loads(request.data)
print "Processing order for: " + order["email"]
cart = order["cart"]

process_order(cart)

return 'Success'
try:
order = json.loads(request.data)
cart = order.get("cart")
if cart is None:
raise ValueError("Missing 'cart' in request body")
print(f"Processing order for: {order.get('email')}")
process_order(cart)
return 'Success'
except (KeyError, ValueError) as e:
sentry_sdk.capture_exception(e)
abort(400, description=str(e))
except Exception as e:
sentry_sdk.capture_exception(e)
abort(500)
Loading