Ejemplo n.º 1
0
async def connect_to_db(app: FastAPI, settings: PostgresSettings) -> None:
    """
    Creates an engine to communicate to the db and retries until
    the db is ready
    """
    logger.debug("Connecting db ...")
    engine: Engine = await create_engine(
        str(settings.dsn),
        application_name=f"{__name__}_{id(app)}",  # unique identifier per app
        minsize=settings.POSTGRES_MINSIZE,
        maxsize=settings.POSTGRES_MAXSIZE,
        dialect=get_dialect(json_serializer=json_serializer),
    )
    logger.debug("Connected to %s", engine.dsn)

    logger.debug("Checking db migrationn ...")
    try:
        await raise_if_migration_not_ready(engine)
    except Exception:
        # NOTE: engine must be closed because retry will create a new engine
        await close_engine(engine)
        raise
    else:
        logger.debug("Migration up-to-date")

    app.state.engine = engine
    logger.debug("Setup engine: %s", get_pg_engine_info(engine))
Ejemplo n.º 2
0
 async def get_new_engine(self, conn_params):
     # важно aiopg при создании engine формирует пул соединений с БД
     # по умолчанию размер пула 10
     return await aiopg.sa.create_engine(
         **conn_params,
         dialect=get_dialect(json_serializer=json_dumps_extend),
     )
Ejemplo n.º 3
0
async def connect_to_db(app: FastAPI, settings: PostgresSettings) -> None:
    logger.debug("Connecting db ...")
    aiopg_dialect = get_dialect(json_serializer=json_serializer)
    engine: Engine = await create_engine(
        str(settings.dsn),
        application_name=f"{__name__}_{id(app)}",  # unique identifier per app
        minsize=settings.POSTGRES_MINSIZE,
        maxsize=settings.POSTGRES_MAXSIZE,
        dialect=aiopg_dialect,
    )
    logger.debug("Connected to %s", engine.dsn)
    app.state.engine = engine

    logger.debug(_compose_info_on_engine(app))
Ejemplo n.º 4
0
async def pg_engine(app):
    conf = app['config']['postgres_db']
    app['db'] = await aiopg.sa.create_engine(
        database=conf['database'],
        user=conf['user'],
        password=conf['password'],
        host=conf['host'],
        port=conf['port'],
        minsize=conf['minsize'],
        maxsize=conf['maxsize'],
        echo=conf['echo'],
        dialect=get_dialect(json_serializer=json_dumps_extend),
        )
    yield
    app['db'].close()
    await app['db'].wait_closed()
Ejemplo n.º 5
0
async def database_ctx(app: web.Application) -> AsyncIterator[None]:
    app['dbpool'] = await create_engine(
        host=app['local_config']['db']['addr'].host,
        port=app['local_config']['db']['addr'].port,
        user=app['local_config']['db']['user'],
        password=app['local_config']['db']['password'],
        dbname=app['local_config']['db']['name'],
        echo=bool(app['local_config']['logging']['level'] == 'DEBUG'),
        minsize=8,
        maxsize=256,
        timeout=60,
        pool_recycle=120,
        dialect=get_dialect(json_serializer=functools.partial(
            json.dumps, cls=ExtendedJSONEncoder), ),
    )
    _update_public_interface_objs(app)
    yield
    app['dbpool'].close()
    await app['dbpool'].wait_closed()