Skip to content

Commit 520d63a

Browse files
committed
black in final (numbered) chapter
1 parent 5268c1e commit 520d63a

File tree

4 files changed

+54
-49
lines changed

4 files changed

+54
-49
lines changed

chapter_06_uow.asciidoc

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -558,7 +558,10 @@ Suppose we want to be able to deallocate and then reallocate orders:
558558
[source,python]
559559
[role="skip"]
560560
----
561-
def reallocate(line: OrderLine, uow: AbstractUnitOfWork) -> str:
561+
def reallocate(
562+
line: OrderLine,
563+
uow: AbstractUnitOfWork,
564+
) -> str:
562565
with uow:
563566
batch = uow.batches.get(sku=line.sku)
564567
if batch is None:
@@ -587,7 +590,10 @@ opened, and half our sofas have fallen into the Indian Ocean. Oops!
587590
[source,python]
588591
[role="skip"]
589592
----
590-
def change_batch_quantity(batchref: str, new_qty: int, uow: AbstractUnitOfWork):
593+
def change_batch_quantity(
594+
batchref: str, new_qty: int,
595+
uow: AbstractUnitOfWork,
596+
):
591597
with uow:
592598
batch = uow.batches.get(reference=batchref)
593599
batch.change_purchased_quantity(new_qty)

chapter_07_aggregate.asciidoc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -865,6 +865,7 @@ def test_concurrent_updates_to_version_are_not_allowed(postgres_session_factory)
865865

866866
<4> And we double-check that only one allocation has gotten through.
867867

868+
// TODO: use """ syntax for sql literal above?
868869

869870

870871
==== Enforcing Concurrency Rules by Using Database Transaction [.keep-together]#Isolation Levels#

chapter_13_dependency_injection.asciidoc

Lines changed: 44 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,8 @@ functions declare an explicit dependency on the UoW:
7575
[role="existing"]
7676
----
7777
def allocate(
78-
cmd: commands.Allocate, uow: unit_of_work.AbstractUnitOfWork
78+
cmd: commands.Allocate,
79+
uow: unit_of_work.AbstractUnitOfWork,
7980
):
8081
----
8182
====
@@ -105,7 +106,6 @@ The UoW itself declares an explicit dependency on the session factory:
105106
[role="existing"]
106107
----
107108
class SqlAlchemyUnitOfWork(AbstractUnitOfWork):
108-
109109
def __init__(self, session_factory=DEFAULT_SESSION_FACTORY):
110110
self.session_factory = session_factory
111111
...
@@ -152,11 +152,12 @@ from allocation.adapters import email, redis_eventpublisher #<1>
152152
...
153153
154154
def send_out_of_stock_notification(
155-
event: events.OutOfStock, uow: unit_of_work.AbstractUnitOfWork,
155+
event: events.OutOfStock,
156+
uow: unit_of_work.AbstractUnitOfWork,
156157
):
157158
email.send( #<2>
158-
159-
f'Out of stock for {event.sku}',
159+
160+
f"Out of stock for {event.sku}",
160161
)
161162
----
162163
====
@@ -217,11 +218,12 @@ ____
217218
[role="non-head"]
218219
----
219220
def send_out_of_stock_notification(
220-
event: events.OutOfStock, send_mail: Callable,
221+
event: events.OutOfStock,
222+
send_mail: Callable,
221223
):
222224
send_mail(
223-
224-
f'Out of stock for {event.sku}',
225+
226+
f"Out of stock for {event.sku}",
225227
)
226228
----
227229
====
@@ -301,7 +303,8 @@ partial functions to compose the function with its dependencies:
301303
----
302304
# existing allocate function, with abstract uow dependency
303305
def allocate(
304-
cmd: commands.Allocate, uow: unit_of_work.AbstractUnitOfWork
306+
cmd: commands.Allocate,
307+
uow: unit_of_work.AbstractUnitOfWork,
305308
):
306309
line = OrderLine(cmd.orderid, cmd.sku, cmd.qty)
307310
with uow:
@@ -346,10 +349,11 @@ which has different dependencies:
346349
[role="skip"]
347350
----
348351
def send_out_of_stock_notification(
349-
event: events.OutOfStock, send_mail: Callable,
352+
event: events.OutOfStock,
353+
send_mail: Callable,
350354
):
351355
send_mail(
352-
356+
353357
...
354358
355359
@@ -381,7 +385,6 @@ classes, though:
381385
# we replace the old `def allocate(cmd, uow)` with:
382386
383387
class AllocateHandler:
384-
385388
def __init__(self, uow: unit_of_work.AbstractUnitOfWork): #<2>
386389
self.uow = uow
387390
@@ -447,7 +450,7 @@ def bootstrap(
447450
if start_orm:
448451
orm.start_mappers() #<1>
449452
450-
dependencies = {'uow': uow, 'send_mail': send_mail, 'publish': publish}
453+
dependencies = {"uow": uow, "send_mail": send_mail, "publish": publish}
451454
injected_event_handlers = { #<3>
452455
event_type: [
453456
inject_dependencies(handler, dependencies)
@@ -546,12 +549,11 @@ but you can, like this:
546549
],
547550
events.OutOfStock: [
548551
lambda e: handlers.send_out_of_stock_notification(e, send_mail)
549-
]
552+
],
550553
}
551554
injected_command_handlers = {
552555
commands.Allocate: lambda c: handlers.allocate(c, uow),
553-
commands.CreateBatch: \
554-
lambda c: handlers.add_batch(c, uow),
556+
commands.CreateBatch: lambda c: handlers.add_batch(c, uow),
555557
commands.ChangeBatchQuantity: \
556558
lambda c: handlers.change_batch_quantity(c, uow),
557559
}
@@ -600,7 +602,6 @@ class:
600602
[role="non-head"]
601603
----
602604
class MessageBus: #<1>
603-
604605
def __init__(
605606
self,
606607
uow: unit_of_work.AbstractUnitOfWork,
@@ -620,7 +621,7 @@ class MessageBus: #<1>
620621
elif isinstance(message, commands.Command):
621622
self.handle_command(message)
622623
else:
623-
raise Exception(f'{message} was not an Event or Command')
624+
raise Exception(f"{message} was not an Event or Command")
624625
----
625626
====
626627

@@ -646,22 +647,21 @@ What else changes in the bus?
646647
def handle_event(self, event: events.Event):
647648
for handler in self.event_handlers[type(event)]: #<1>
648649
try:
649-
logger.debug('handling event %s with handler %s', event, handler)
650+
logger.debug("handling event %s with handler %s", event, handler)
650651
handler(event) #<2>
651652
self.queue.extend(self.uow.collect_new_events())
652653
except Exception:
653-
logger.exception('Exception handling event %s', event)
654+
logger.exception("Exception handling event %s", event)
654655
continue
655656
656-
657657
def handle_command(self, command: commands.Command):
658-
logger.debug('handling command %s', command)
658+
logger.debug("handling command %s", command)
659659
try:
660660
handler = self.command_handlers[type(command)] #<1>
661661
handler(command) #<2>
662662
self.queue.extend(self.uow.collect_new_events())
663663
except Exception:
664-
logger.exception('Exception handling command %s', command)
664+
logger.exception("Exception handling command %s", command)
665665
raise
666666
----
667667
====
@@ -696,15 +696,15 @@ rest of it:
696696
+bus = bootstrap.bootstrap()
697697
698698
699-
@app.route("/add_batch", methods=['POST'])
699+
@app.route("/add_batch", methods=["POST"])
700700
@@ -19,8 +16,7 @@ def add_batch():
701701
cmd = commands.CreateBatch(
702-
request.json['ref'], request.json['sku'], request.json['qty'], eta,
702+
request.json["ref"], request.json["sku"], request.json["qty"], eta
703703
)
704704
- uow = unit_of_work.SqlAlchemyUnitOfWork() #<2>
705705
- messagebus.handle(cmd, uow)
706706
+ bus.handle(cmd) #<3>
707-
return 'OK', 201
707+
return "OK", 201
708708
709709
----
710710
====
@@ -749,13 +749,14 @@ def sqlite_bus(sqlite_session_factory):
749749
yield bus
750750
clear_mappers()
751751
752+
752753
def test_allocations_view(sqlite_bus):
753-
sqlite_bus.handle(commands.CreateBatch('sku1batch', 'sku1', 50, None))
754-
sqlite_bus.handle(commands.CreateBatch('sku2batch', 'sku2', 50, today))
754+
sqlite_bus.handle(commands.CreateBatch("sku1batch", "sku1", 50, None))
755+
sqlite_bus.handle(commands.CreateBatch("sku2batch", "sku2", 50, today))
755756
...
756-
assert views.allocations('order1', sqlite_bus.uow) == [
757-
{'sku': 'sku1', 'batchref': 'sku1batch'},
758-
{'sku': 'sku2', 'batchref': 'sku2batch'},
757+
assert views.allocations("order1", sqlite_bus.uow) == [
758+
{"sku": "sku1", "batchref": "sku1batch"},
759+
{"sku": "sku2", "batchref": "sku2batch"},
759760
]
760761
----
761762
====
@@ -856,25 +857,23 @@ email, could be SMS, could be Slack posts one day.
856857
[source,python]
857858
----
858859
class AbstractNotifications(abc.ABC):
859-
860860
@abc.abstractmethod
861861
def send(self, destination, message):
862862
raise NotImplementedError
863863
864864
...
865865
866866
class EmailNotifications(AbstractNotifications):
867-
868867
def __init__(self, smtp_host=DEFAULT_HOST, port=DEFAULT_PORT):
869868
self.server = smtplib.SMTP(smtp_host, port=port)
870869
self.server.noop()
871870
872871
def send(self, destination, message):
873-
msg = f'Subject: allocation service notification\n{message}'
872+
msg = f"Subject: allocation service notification\n{message}"
874873
self.server.sendmail(
875-
from_addr='[email protected]',
874+
from_addr="[email protected]",
876875
to_addrs=[destination],
877-
msg=msg
876+
msg=msg,
878877
)
879878
----
880879
====
@@ -912,7 +911,6 @@ We work through and define a fake version for unit testing:
912911
[source,python]
913912
----
914913
class FakeNotifications(notifications.AbstractNotifications):
915-
916914
def __init__(self):
917915
self.sent = defaultdict(list) # type: Dict[str, List[str]]
918916
@@ -939,7 +937,7 @@ And we use it in our tests:
939937
)
940938
bus.handle(commands.CreateBatch("b1", "POPULAR-CURTAINS", 9, None))
941939
bus.handle(commands.Allocate("o1", "POPULAR-CURTAINS", 10))
942-
assert fake_notifs.sent['[email protected]'] == [
940+
assert fake_notifs.sent["[email protected]"] == [
943941
f"Out of stock for POPULAR-CURTAINS",
944942
]
945943
----
@@ -1014,19 +1012,19 @@ def bus(sqlite_session_factory):
10141012
10151013
10161014
def get_email_from_mailhog(sku): #<2>
1017-
host, port = map(config.get_email_host_and_port().get, ['host', 'http_port'])
1018-
all_emails = requests.get(f'http://{host}:{port}/api/v2/messages').json()
1019-
return next(m for m in all_emails['items'] if sku in str(m))
1015+
host, port = map(config.get_email_host_and_port().get, ["host", "http_port"])
1016+
all_emails = requests.get(f"http://{host}:{port}/api/v2/messages").json()
1017+
return next(m for m in all_emails["items"] if sku in str(m))
10201018
10211019
10221020
def test_out_of_stock_email(bus):
10231021
sku = random_sku()
1024-
bus.handle(commands.CreateBatch('batch1', sku, 9, None)) #<3>
1025-
bus.handle(commands.Allocate('order1', sku, 10))
1022+
bus.handle(commands.CreateBatch("batch1", sku, 9, None)) #<3>
1023+
bus.handle(commands.Allocate("order1", sku, 10))
10261024
email = get_email_from_mailhog(sku)
1027-
assert email['Raw']['From'] == '[email protected]' #<4>
1028-
assert email['Raw']['To'] == ['[email protected]']
1029-
assert f'Out of stock for {sku}' in email['Raw']['Data']
1025+
assert email["Raw"]["From"] == "[email protected]" #<4>
1026+
assert email["Raw"]["To"] == ["[email protected]"]
1027+
assert f"Out of stock for {sku}" in email["Raw"]["Data"]
10301028
----
10311029
====
10321030

0 commit comments

Comments
 (0)