Advertisement
BERKYT

Dependency injection and dependency_injector

Aug 21st, 2022 (edited)
931
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. import random
  2.  
  3.  
  4. def _dependency_injection():
  5.     from abc import ABC, abstractmethod
  6.  
  7.     class DataBaseAbstract(ABC):
  8.         @abstractmethod
  9.         def connect(self):
  10.             pass
  11.  
  12.     class SQLite(DataBaseAbstract):
  13.         def connect(self):
  14.             print('SQLite: connection with sqlite is completed')
  15.  
  16.     class MySQL(DataBaseAbstract):
  17.         def connect(self):
  18.             print('MySQL: connection with sqlite is completed')
  19.  
  20.     class DataBase:
  21.         def __init__(self, db: DataBaseAbstract):
  22.             self.db: DataBaseAbstract = db
  23.  
  24.         def get_column(self):
  25.             self.db.connect()
  26.  
  27.     db_sqlite: DataBase = DataBase(SQLite())
  28.     db_sqlite.get_column()
  29.  
  30.     db_mysql: DataBase = DataBase(MySQL())
  31.     db_mysql.get_column()
  32.  
  33.  
  34. def _dependency_injector():
  35.     from dependency_injector import containers, providers
  36.  
  37.     class Sensor:
  38.         def __init__(self, ip, id):
  39.             self.ip = ip
  40.             self.id = id
  41.  
  42.     class Server:
  43.         def __init__(self, clients: [Sensor]):
  44.             self.clients: [Sensor] = clients
  45.  
  46.     class Container(containers.DeclarativeContainer):
  47.         config = providers.Configuration()
  48.  
  49.         server = providers.Singleton(
  50.             Server,
  51.             clients=config.clients
  52.         )
  53.  
  54.         sensor = providers.Factory(
  55.             Sensor,
  56.             ip=config.ip,
  57.             id=config.id
  58.         )
  59.  
  60.     container = Container()
  61.     server = container.server()
  62.     server.clients = [Sensor('127.0.0.1', random.randint(1, 100)) for _ in range(10)]
  63.  
  64.     print(server.clients)
  65.     print(server.clients[0].ip)
  66.  
  67.  
  68. if __name__ == '__main__':
  69.     _dependency_injection()
  70.     _dependency_injector()
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement