Next / Previous / Contents / NM Tech homepage

8.4. MyCBC.__init__()

mycbc.py
# - - -   M y C B C . _ _ i n i t _ _

    def __init__(self, password):
        '''Constructor for MyCBC
        '''
        #-- 1 --
        # [ if MySQL database is available and accepts
        #   password (password) ->
        #     self.engine  :=  an sqlalchemy.engine.Engine instance
        #         that connects to the database with (password) ]
        #   else -> raise sqlalchemy.exc.SQLAlchemyError ]
        url = ( URL_FORMAT %
                (PROTOCOL, DB_USER, password, DB_HOST, DB_NAME) )
        self.engine = engine.create_engine(url)

        #-- 2 --
        # [ self.meta  :=  metadata reflected from self.engine
        #       as a schema.MetaData instance ]
        self.meta = schema.MetaData(bind=self.engine, reflect=True)

        #-- 3 --
        # [ self.Session  :=  a constructor for sessions using
        #                     self.engine
        #   self.s  :=  an instance of that constructor ]
        self.Session = orm.sessionmaker ( bind=self.engine,
            autoflush=True, autocommit=False, expire_on_commit=True )
        self.s = self.Session()

The constructor for this class is generally similar to the one in Section 6.14, “CBCData.__init__(): Constructor”. The primary difference is that the schema is obtained by reflection, so we don't need to declare the Table instances.

Once the metadata is connected to the engine with the reflect=True option, we will use an undocumented feature of SQLAlchemy: the MetaData instance has an attribute .tables, which is a dictionary whose keys are the names of the reflected tables, and each related value is the corresponding Table instance. See Section 8.5, “MyCBC.__mapTable: Locate and bind a table”.

mycbc.py
        #-- 4 --
        # [ tables CIR_NAME, STND_NAME, AS_PUB_NAME, EFF_NAME,
        #   and CEN_NAME are in self.meta ->
        #     self.Cir  :=  a class mapped to table CIR_NAME
        #     self.Stnd  :=  a class mapped to table STND_NAME
        #     self.AsPub  :=  a class mapped to table AS_PUB_NAME
        #     self.Eff  :=  a class mapped to table EFF_NAMe
        #     self.Cen  :=  a class mapped to table CEN_NAME ]
        self.__mapTable(CIR_NAME, self.Cir)
        self.__mapTable(STND_NAME, self.Stnd)
        self.__mapTable(AS_PUB_NAME, self.AsPub)
        self.__mapTable(EFF_NAME, self.Eff)
        self.__mapTable(CEN_NAME, self.Cen)