def tmpdb(): """Get a handle to an empty temporary database that is wiped on teardown.""" from brainscopypaste.conf import settings engine = create_engine( 'postgresql+psycopg2://{user}:{pw}@localhost:5432/{db}' .format(user=settings.DB_USER, pw=settings.DB_PASSWORD, db=settings.DB_NAME_TEST), client_encoding='utf8') Session.configure(bind=engine) Base.metadata.drop_all(engine) Base.metadata.create_all(engine) yield Base.metadata.drop_all(engine)
def init_db(echo_sql=False): """Connect to the database and bind :mod:`.db`'s `Session` object to it. Uses the :data:`~.settings.DB_USER` and :data:`~.settings.DB_PASSWORD` credentials to connect to PostgreSQL database :data:`~.settings.DB_NAME`. It binds the `Session` object in :mod:`.db` to this engine, and returns the engine object. Note that once this is done, you can directly use :func:`session_scope` since it uses the right `Session` object. Parameters ---------- echo_sql : bool, optional If `True`, print to stdout all SQL commands sent to the engine; defaults to `False`. Returns ------- :class:`sqlalchemy.engine.Engine` The engine connected to the database. """ from brainscopypaste.db import Base, Session from brainscopypaste.conf import settings logger.info('Initializing database connection') engine = create_engine( 'postgresql+psycopg2://{user}:{pw}@localhost:5432/{db}' .format(user=settings.DB_USER, pw=settings.DB_PASSWORD, db=settings.DB_NAME), client_encoding='utf8', echo=echo_sql) Session.configure(bind=engine) logger.info('Database connected') logger.debug('Checking tables to create') Base.metadata.create_all(engine) return engine