<s> from collections import defaultdict <EOL> from sqlalchemy import create_engine , event <EOL> from sqlalchemy . orm import scoped_session , sessionmaker , mapper <EOL> from . model import ModelBase <EOL> _SETUP = defaultdict ( lambda : False ) <EOL> _ENGINES = { } <EOL> _SESSIONS = { } <EOL> def get_engine ( dburi , ** kwargs ) : <EOL> if dburi not in _ENGINES : <EOL> _ENGINES [ dburi ] = create_engine ( dburi , ** kwargs ) <EOL> return _ENGINES [ dburi ] <EOL> def session_for ( dburi , ** kwargs ) : <EOL> engine = get_engine ( dburi , ** kwargs ) <EOL> if dburi not in _SESSIONS : <EOL> _SESSIONS [ dburi ] = scoped_session ( sessionmaker ( bind = engine ) ) <EOL> ModelBase . query = _SESSIONS [ dburi ] . query_property ( ) <EOL> @ event . listens_for ( mapper , '<STR_LIT>' ) <EOL> def auto_add ( target , args , kwargs ) : <EOL> if isinstance ( target , ModelBase ) : <EOL> _SESSIONS [ dburi ] . add ( target ) <EOL> if not _SETUP [ '<STR_LIT>' ] : <EOL> ModelBase . metadata . create_all ( engine ) <EOL> _SETUP [ '<STR_LIT>' ] = True <EOL> return _SESSIONS [ dburi ] </s>
