Skip to content

Commit ab8c084

Browse files
committed
modify flask and redis to use messagebus [chapter_07_external_events_ends]
1 parent 691de96 commit ab8c084

File tree

2 files changed

+10
-13
lines changed

2 files changed

+10
-13
lines changed

src/allocation/flask_app.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from datetime import datetime
22
from flask import Flask, jsonify, request
3-
from allocation import exceptions, orm, handlers, unit_of_work
3+
from allocation import events, exceptions, messagebus, orm, unit_of_work
44

55
app = Flask(__name__)
66
orm.start_mappers()
@@ -11,22 +11,21 @@ def add_batch():
1111
eta = request.json['eta']
1212
if eta is not None:
1313
eta = datetime.fromisoformat(eta).date()
14-
handlers.add_batch(
14+
event = events.BatchCreated(
1515
request.json['ref'], request.json['sku'], request.json['qty'], eta,
16-
unit_of_work.SqlAlchemyUnitOfWork(),
1716
)
17+
messagebus.handle([event], unit_of_work.SqlAlchemyUnitOfWork())
1818
return 'OK', 201
1919

2020

2121
@app.route("/allocate", methods=['POST'])
2222
def allocate_endpoint():
2323
try:
24-
batchref = handlers.allocate(
25-
request.json['orderid'],
26-
request.json['sku'],
27-
request.json['qty'],
28-
unit_of_work.SqlAlchemyUnitOfWork(),
24+
event = events.AllocationRequest(
25+
request.json['orderid'], request.json['sku'], request.json['qty'],
2926
)
27+
results = messagebus.handle([event], unit_of_work.SqlAlchemyUnitOfWork())
28+
batchref = results.pop()
3029
except exceptions.InvalidSku as e:
3130
return jsonify({'message': str(e)}), 400
3231

src/allocation/redis_pubsub.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from dataclasses import asdict
44
import redis
55

6-
from allocation import config, orm
6+
from allocation import config, events, orm, messagebus, unit_of_work
77

88
logger = logging.getLogger(__name__)
99

@@ -22,10 +22,8 @@ def main():
2222
def handle_change_batch_quantity(m):
2323
logging.debug('handling %s', m)
2424
data = json.loads(m['data'])
25-
handlers.change_batch_quantity(
26-
ref=data['batchref'], qty=data['qty'],
27-
uow=unit_of_work.SqlAlchemyUnitOfWork(),
28-
)
25+
event = events.BatchQuantityChanged(ref=data['batchref'], qty=data['qty'])
26+
messagebus.handle([event], uow=unit_of_work.SqlAlchemyUnitOfWork())
2927

3028

3129
def publish(channel, event):

0 commit comments

Comments
 (0)