1
1
import os
2
2
import json
3
+ import logging
3
4
4
5
import boto3
5
6
from botocore .exceptions import ClientError
6
7
7
8
9
+ logging .basicConfig (
10
+ level = logging .INFO ,
11
+ format = "[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s" ,
12
+ datefmt = "%Y-%m-%d %H:%M:%S %z"
13
+ )
14
+
15
+ logger = logging .getLogger (__name__ )
16
+
17
+
8
18
def get_secret (secret_name ):
9
19
client = boto3 .client ("secretsmanager" )
10
20
@@ -13,6 +23,7 @@ def get_secret(secret_name):
13
23
SecretId = secret_name
14
24
)
15
25
except ClientError as e :
26
+ logger .error (f"Failed to retrieve secret." )
16
27
raise e
17
28
18
29
secret = get_secret_value_response ["SecretString" ]
@@ -22,26 +33,36 @@ def get_secret(secret_name):
22
33
def get_database_uri ():
23
34
database_uri = os .getenv ("DATABASE_URI" )
24
35
if database_uri :
36
+ logger .info ("Using DATABASE_URI from environment." )
25
37
return database_uri
26
38
27
39
db_credentials_secret_name = os .getenv ("DATABASE_CREDENTIALS_SECRET_NAME" )
28
40
if db_credentials_secret_name :
41
+ logger .info (f"Retrieving database credentials from Secrets Manager" )
29
42
secret = get_secret (db_credentials_secret_name )
30
43
db_username = secret ["username" ]
31
44
db_password = secret ["password" ]
32
45
db_host = secret ["host" ]
33
46
db_database = secret ["dbname" ]
34
47
else :
48
+ logger .info ("Retrieving database credentials from environment variables." )
35
49
db_username = os .getenv ("DB_USERNAME" )
36
50
db_password = os .getenv ("DB_PASSWORD" )
37
51
db_host = os .getenv ("DB_HOST" )
38
52
db_database = os .getenv ("DB_DATABASE" )
39
53
54
+ if not all ([db_username , db_password , db_host , db_database ]):
55
+ logger .info ("Database credentials are not fully specified, override with test database URI." )
56
+ return "" # Override in tests.
57
+
40
58
return f"mysql+mysqlconnector://{ db_username } :{ db_password } @{ db_host } /{ db_database } ?charset=utf8mb4"
41
59
42
60
43
61
class Config :
44
- TESTING = False
45
62
LOG_LEVEL = os .getenv ("LOG_LEVEL" )
46
63
SQLALCHEMY_DATABASE_URI = get_database_uri ()
47
- SQLALCHEMY_TRACK_MODIFICATIONS = False
64
+ SQLALCHEMY_TRACK_MODIFICATIONS = False
65
+ SQLALCHEMY_ENGINE_OPTIONS = {
66
+ "pool_pre_ping" : True ,
67
+ "echo" : os .getenv ("FLASK_ENV" ) != "production"
68
+ }
0 commit comments