This repository was archived by the owner on Dec 23, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
44 lines (35 loc) · 1.25 KB
/
db.py
File metadata and controls
44 lines (35 loc) · 1.25 KB
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
38
39
40
41
42
43
44
import os
from contextlib import contextmanager
from time import sleep
# noinspection PyUnresolvedReferences
import __main__
NUM_RETRIES = 5
SLEEP_DELAY = 2
def setup_db(service_name):
from sqlalchemy import create_engine
global engine
engine = create_engine(os.getenv("DATABASE_URL", "mysql://localhost/{}".format(service_name)))
@contextmanager
def connect_db():
from sqlalchemy.exc import OperationalError
def db(*args):
for _ in range(NUM_RETRIES):
with engine.connect() as conn:
try:
try:
if isinstance(args[1][0], str):
raise TypeError
except (IndexError, TypeError):
return conn.execute(*args)
else:
for data in args[1]:
conn.execute(args[0], data, *args[2:])
except OperationalError as e:
print("MySQL Failure, retrying in {} seconds...".format(SLEEP_DELAY), e)
sleep(SLEEP_DELAY)
continue
else:
break
else:
print("{} repeated failures, transaction failed".format(NUM_RETRIES))
yield db