From 91462a39a51f91973969e6a03a8c2f7d161e1d95 Mon Sep 17 00:00:00 2001 From: Gusev Anton <gusev_aa@groupbwt.com> Date: Thu, 13 Jun 2019 17:12:12 +0300 Subject: [PATCH] change Connector for use singleton --- src/database/Connector.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/database/Connector.py b/src/database/Connector.py index ae84339..808ba27 100644 --- a/src/database/Connector.py +++ b/src/database/Connector.py @@ -3,17 +3,25 @@ from sqlalchemy.orm import sessionmaker from scrapy.conf import settings -class Connector: - connection = None - engine = create_engine(settings['CONNECTION_STRING']) - Session = sessionmaker(bind=engine) +class Singleton(type): + _instances = {} + def __call__(cls, *args, **kwargs): + if cls not in cls._instances: + cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) + return cls._instances[cls] + + +class Connector(metaclass=Singleton): + __connection = None + __engine = create_engine(settings['CONNECTION_STRING']) + __Session = sessionmaker(bind=__engine) @staticmethod def get_session(): - return Connector.Session() + return Connector.__Session() @staticmethod def get_connection(): - if not Connector.connection: - Connector.connection = Connector.engine.connect() - return Connector.connection + if not Connector.__connection: + Connector.__connection = Connector.__engine.connect() + return Connector.__connection -- GitLab