-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
149 lines (121 loc) · 3.83 KB
/
app.py
File metadata and controls
149 lines (121 loc) · 3.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
from flask import Flask, jsonify, request
import mysql.connector
app = Flask(__name__)
# --- Database Connection ---
def get_db():
#---- LOCAL MySQL (localhost) ----
# return mysql.connector.connect(
# host="localhost",
# user="root",
# password="yourpassword",
# database="mydb"
# )
# ---- AWS RDS (cloud) ----
return mysql.connector.connect(
host="myshop-db.c74w0qcqe775.eu-north-1.rds.amazonaws.com",
user="admin",
password="JijRho9ieaAhAqMSqucc",
database="mydb",
port=3306
)
# --- ROUTE 1: Home ---
@app.route('/')
def home():
return jsonify({
"message": "Welcome to my Shop API! 🛒",
"routes": [
"/products - See all products",
"/orders - See all orders",
"/order - Place an order (POST)"
]
})
# --- ROUTE 2: Get all products ---
@app.route('/products')
def get_products():
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT * FROM products")
results = cursor.fetchall()
conn.close()
products = []
for row in results:
products.append({
"id": row[0],
"name": row[1],
"price": float(row[2]),
"stock": row[3]
})
return jsonify(products)
# --- ROUTE 3: Get all orders ---
@app.route('/orders')
def get_orders():
conn = get_db()
cursor = conn.cursor()
query = """
SELECT orders.id, users.name, products.name,
order_items.quantity, products.price, orders.order_date
FROM orders
INNER JOIN users ON orders.user_id = users.id
INNER JOIN order_items ON orders.id = order_items.order_id
INNER JOIN products ON order_items.product_id = products.id
"""
cursor.execute(query)
results = cursor.fetchall()
conn.close()
orders = []
for row in results:
orders.append({
"order_id": row[0],
"customer": row[1],
"product": row[2],
"quantity": row[3],
"total": float(row[4] * row[3]),
"date": str(row[5])
})
return jsonify(orders)
# --- ROUTE 4: Place an order (POST) ---
@app.route('/order', methods=['POST'])
def place_order():
data = request.get_json()
user_id = data['user_id']
product_id = data['product_id']
quantity = data['quantity']
conn = get_db()
cursor = conn.cursor()
# Check stock
cursor.execute("SELECT stock, name, price FROM products WHERE id = %s", (product_id,))
product = cursor.fetchone()
if not product:
return jsonify({"error": "Product not found!"}), 404
if product[0] < quantity:
return jsonify({"error": f"Not enough stock! Only {product[0]} left."}), 400
# Create order
cursor.execute(
"INSERT INTO orders (user_id, order_date) VALUES (%s, CURDATE())",
(user_id,)
)
order_id = cursor.lastrowid
# Add order item
cursor.execute(
"INSERT INTO order_items (order_id, product_id, quantity) VALUES (%s, %s, %s)",
(order_id, product_id, quantity)
)
# Deduct stock
cursor.execute(
"UPDATE products SET stock = stock - %s WHERE id = %s",
(quantity, product_id)
)
conn.commit()
conn.close()
total = product[2] * quantity
return jsonify({
"message": f"✅ Order placed!",
"product": product[1],
"quantity": quantity,
"total": float(total)
})
# --- Run the app ---
if __name__ == '__main__':
app.run(debug=True)
### Step 3 — Run it! Run `app.py` in PyCharm and you should see:* Running on http://127.0.0.1:5000* Debug mode: on
### Step 4 — Open your browser and test: Visit these URLs one by one:**Home:**http://127.0.0.1:5000/```**See all products:**```http://127.0.0.1:5000/products```**See all orders:**```http://127.0.0.1:5000/orders