-
Notifications
You must be signed in to change notification settings - Fork 1
/
warehouse.py
52 lines (37 loc) · 1.67 KB
/
warehouse.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
from concurrent import futures
import logging
from google.protobuf import message
import grpc
import common_pb2
import warehouse_pb2
import warehouse_pb2_grpc
class Warehouse(warehouse_pb2_grpc.WarehouseServicer):
order_id = 0
reservations = {}
def Reserve(self, request, context):
self.order_id = self.order_id + 1
warehouse_id = 'WH' + str(self.order_id).zfill(5)
self.reservations[warehouse_id] = request
print(f"Book '{request.isbn}'' for user is reserved with id '{warehouse_id}'", flush=True)
return warehouse_pb2.WarehouseReply(id=warehouse_id, message="RESERVED")
def Reservations(self, request, context):
def response_messages():
for reservation in self.reservations.values():
response = common_pb2.Order(isbn=reservation.isbn, buyer=reservation.buyer, quantity=reservation.quantity)
yield response
return response_messages()
def Dispatch(self, request, context):
if request.id not in self.reservations:
return warehouse_pb2.WarehouseReply(id=request.id, message="RESERVATION NOT FOUND")
reservation = self.reservations.pop(request.id)
print(f"Book '{reservation.isbn}' reserved with id '{request.id}' is dispatched now", flush=True)
return warehouse_pb2.WarehouseReply(id=request.id, message="CONFIRMED")
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
warehouse_pb2_grpc.add_WarehouseServicer_to_server(Warehouse(), server)
server.add_insecure_port('[::]:8001')
server.start()
server.wait_for_termination()
if __name__ == '__main__':
logging.basicConfig()
serve()