From da71062508f53d2674e1b9ea90764b7ba650c412 Mon Sep 17 00:00:00 2001 From: schneefux Date: Tue, 7 Feb 2017 20:09:32 +0100 Subject: db connection params from env, fix early start --- api.py | 8 +++++++- database.py | 15 +++++++++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/api.py b/api.py index c5b220a..cf692c3 100644 --- a/api.py +++ b/api.py @@ -86,7 +86,13 @@ async def api_status(_): loop = asyncio.get_event_loop() -loop.run_until_complete(db.connect("postgres://vgstats@postgres/vgstats")) +loop.run_until_complete(db.connect( + host=os.environ["POSTGRESQL_HOST"], + port=os.environ["POSTGRESQL_PORT"], + user=os.environ["POSTGRESQL_USER"], + password=os.environ["POSTGRESQL_PASSWORD"], + database=os.environ["POSTGRESQL_DB"] +)) loop.run_until_complete(queries.load_queries("/apps/api/queries")) loop.create_task(recrawl()) app = aiohttp.web.Application(loop=loop) diff --git a/database.py b/database.py index 0679a52..45467f6 100644 --- a/database.py +++ b/database.py @@ -10,13 +10,24 @@ class Database(object): def __init__(self): self._pool = None - async def connect(self, connstring): + async def connect(self, host, port, user, password, database): """Connects to the database. :param connstring: Connection string containing user and database. :type connstring: str """ - self._pool = await asyncpg.create_pool(connstring) + while True: # retry until connection succeeds + try: + print("attempting to connect to db…") + self._pool = await asyncpg.create_pool( + host=host, port=port, user=user, + password=password, database=database) + break + except asyncpg.exceptions.CannotConnectNowError: + await self._pool.close() + print("Database is not ready yet. Retrying…") + await asyncio.sleep(5) + async def upsert_type(self, obj, objtype, many=False): """Upserts an object of given `objtype` into the corresponding database. -- cgit v1.3.1