-
Notifications
You must be signed in to change notification settings - Fork 0
/
cart.py
159 lines (112 loc) Β· 3.75 KB
/
cart.py
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
150
151
152
153
154
155
156
157
158
159
import os
import uuid
from collections import namedtuple
from typing import Dict
import consul
import requests
from consul import Check
from flask import Flask, jsonify, abort, request
app = Flask(__name__)
Item = namedtuple('Item', ['id', 'name', 'price'])
CartEntry = namedtuple('CartEntry', ['id', 'item', 'quantity'])
config = {
'CHECKOUT_URL': ''
}
class ShoppingCart:
def __init__(self, cart_id: str, items: Dict[str, CartEntry] = {}):
self.id = cart_id
self.items: Dict[str, CartEntry] = items
def add_item(self, item: Item, quantity: int) -> CartEntry:
# if item is not None and quantity >= 1:
cart_entry_id = str(uuid.uuid4())
entry = CartEntry(cart_entry_id, item, quantity)
self.items[cart_entry_id] = entry
return entry
def remove_item(self, cart_entry_id: str):
del self.items[cart_entry_id]
def total_price(self) -> int:
return sum([entry.item.price * entry.quantity for entry in self.items.values()])
def jsonify(self):
return {
'id': self.id,
'total': self.total_price(),
'items': self.items
}
carts: Dict[str, ShoppingCart] = {}
@app.route('/healthcheck')
def check():
return 'OK'
@app.route("/carts", methods=['POST'])
def create_cart():
cart_id = str(uuid.uuid4())
cart = ShoppingCart(cart_id)
carts[cart_id] = cart
return jsonify(cart.jsonify())
@app.route("/carts/<cart_id>", methods=['GET'])
def get_cart(cart_id):
try:
cart = carts[cart_id]
return jsonify(cart.jsonify())
except KeyError:
abort(404, description='Cart not found')
def ok():
return {'message': 'OK'}
@app.route("/carts/<cart_id>/add", methods=['PUT'])
def add_to_cart(cart_id):
try:
cart_entry_json = request.json
item_json = cart_entry_json['item']
quantity = cart_entry_json['quantity']
item_id = item_json['id']
item_name = item_json['name']
item_price = item_json['price']
item = Item(item_id, item_name, item_price)
except KeyError:
abort(400, description='Bad request')
return
try:
cart = carts[cart_id]
cart.add_item(item, quantity)
return ok()
except KeyError:
abort(404, 'Cart not found')
@app.route("/carts/<cart_id>/checkout", methods=['PUT'])
def checkout_cart(cart_id):
try:
cart = carts[cart_id]
except KeyError:
abort(404, 'Cart not found')
return
url = f"{config['CHECKOUT_URL']}/checkout"
checkout_request = {
'order_id': cart_id,
'amount': cart.total_price()
}
req = requests.put(url, json=checkout_request)
if req.status_code == 200:
checkout_response = req.json()
return jsonify({
'checkout_id': checkout_response[0]
})
raise Exception('Internal server error')
@app.errorhandler(404)
def not_found(e):
return jsonify({'message': e.description}), 404
@app.errorhandler(400)
def bad_request(e):
return jsonify({'message': e.description}), 400
# @app.route("/carts/<cart_id>/remove/<cart_entry_id>, methods=['DELETE'])
def main():
# consul client create
c = consul.Consul()
# health check
check_http = Check.http('http://127.0.0.1:5001/healthcheck', interval='5s', timeout='10s', deregister=True)
# registration of cart service
c.agent.service.register('cart', address=os.getenv("LISTEN_ADDR", "127.0.0.1"), port=5001, check=check_http)
# discovery
services = c.catalog.service('checkout')[1][0]
# url for checkout micro-service
config['CHECKOUT_URL'] = f"http://{services['ServiceAddress']}:{services['ServicePort']}"
app.run(debug=True, host='0.0.0.0', port=5001)
if __name__ == '__main__':
main()