Skip to content

Commit dac83a8

Browse files
committed
Add success or failure to vend endpoint
1 parent e47adf4 commit dac83a8

File tree

2 files changed

+25
-10
lines changed

2 files changed

+25
-10
lines changed

machine_controller/app.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,15 +47,23 @@ def hello_world():
4747
abort(401)
4848
data = request.json()
4949
items = data['items']
50+
transaction_id = data['transaction_id']
5051

52+
53+
statuses = []
5154
for i, item in enumerate(items):
5255
try:
5356
merch.vend(item[0], int(item[1]))
54-
except:
55-
# Some error occurred, return the first index that failed
56-
return jsonify(success=False, failed=i)
57+
statuses.append({'error': None, 'location': item})
58+
59+
except Exception as e:
60+
# Some error occurred while vending
61+
# I'd prefer to catch Merch.VendError's only, but if something else
62+
# goes wrong, we still need to let the client know instead of
63+
# throwing a 500
64+
statuses.append({'error': str(e), 'location': item})
5765

58-
return jsonify(success=True)
66+
return jsonify(transaction_id=transaction_id, items=statuses)
5967

6068
if __name__ == '__main__':
6169
# Make sure flask runs in a single thread. Otherwise concurrent requests

machine_controller/vend.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,11 @@ class Merch:
4444
MAX_LETTER = 'F'
4545
MAX_NUMBER = '0'
4646

47+
class VendError(Exception):
48+
pass
49+
50+
InvalidLocationError = VendError("Invalid location")
51+
4752
def __init__(self, debug=False):
4853
self.debug = debug
4954

@@ -93,22 +98,24 @@ def vend(self, letter, number):
9398
try:
9499
char = ord(letter)
95100
except TypeError:
96-
raise TypeError('Letter %s does not represent a character' %
97-
str(letter))
101+
raise Merch.VendError("Invalid location: %s" %
102+
(str(letter) + str(number)))
98103

99104
# Maybe we should use the actual keypad value?
100105
if char < ord('A') or char > ord('Z'):
101-
raise ValueError('Invalid Letter: %s' % str(letter))
106+
raise Merch.VendError("Invalid location: %s" %
107+
(str(letter) + str(number)))
102108

103109
num = 0
104110
try:
105111
num = int(number)
106112
except TypeError:
107-
raise TypeError('Number %s is not convertible to an integer' %
108-
str(num))
113+
raise Merch.VendError("Invalid location: %s" %
114+
(str(letter) + str(number)))
109115

110116
if num < 0 or num > 10:
111-
raise ValueError('Number %d is not in the range 1-10' % num)
117+
raise Merch.VendError("Invalid location: %s" %
118+
(str(letter) + str(number)))
112119

113120
self.__vend(letter, str(number))
114121

0 commit comments

Comments
 (0)