from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from scrapy.conf import settings 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() @staticmethod def get_connection(): if not Connector.__connection: Connector.__connection = Connector.__engine.connect() return Connector.__connection