Sergiusz Bazanski | 1fad2e5 | 2019-08-01 20:16:27 +0200 | [diff] [blame] | 1 | import logging |
| 2 | |
| 3 | from flask import current_app |
| 4 | from flask import _app_ctx_stack as stack |
| 5 | import grpc |
| 6 | |
| 7 | |
| 8 | logger = logging.getLogger(__name__) |
| 9 | |
| 10 | |
| 11 | class 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 |