forked from gestaogovbr/api-pgd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_after_db.py
executable file
·37 lines (31 loc) · 1.07 KB
/
run_after_db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/local/bin/python
"""Bootstraps the FastAPI application, first waiting for the Postgres
database to be up and running.
"""
import os
import time
import argparse
from sqlalchemy import text as sa_text, create_engine
from sqlalchemy.exc import OperationalError
MAX_RETRIES = 120
parser = argparse.ArgumentParser(description=
'Wait for the database to be responsive and then runs a command.')
parser.add_argument(
'command_line',
nargs='+',
help=('The command to run after the database is online. '
'Please encase the command in quotes.'))
args = parser.parse_args()
command = ' '.join(args.command_line) # pylint: disable=invalid-name
engine = create_engine(os.environ['SQLALCHEMY_DATABASE_URL'])
for _ in range(MAX_RETRIES):
try:
with engine.connect() as connection:
connection.execute(sa_text("select 'TEST';"))
print('Postgres database found.')
break
except OperationalError as e:
print('Postgres database unavailable, waiting...')
time.sleep(1)
print('Executing command: ', command)
os.system(command)