blob: d7230d3d165839af34d6eaa1a039a5912d09c5a4 [file] [log] [blame]
Sergiusz Bazanski1fad2e52019-08-01 20:16:27 +02001import logging
2
3from flask import current_app
4from flask import _app_ctx_stack as stack
5import grpc
6
7
8logger = logging.getLogger(__name__)
9
10
11class Channel:
12 def __init__(self, app, address):
13 self.app = app
14 self.address = address
15 self.stubs = {}
16 app.teardown_appcontext(self.teardown)
17
18 def _connect(self):
19 logger.info("Connecting to {}...".format(self.address))
20 return grpc.insecure_channel(self.address)
21
22 @property
23 def conn(self):
24 ctx = stack.top
25 if ctx is not None:
26 if not hasattr(ctx, 'conn'):
27 ctx.conn = self._connect()
28 return ctx.conn
29
30 def stub(self, stub):
31 if stub not in self.stubs:
32 self.stubs[stub] = stub(self.conn)
33 return self.stubs[stub]
34
35 def teardown(self, exception):
36 ctx = stack.top
37 if hasattr(ctx, 'conn'):
38 del ctx.conn