88
99from backend .common .config import config
1010
11+ import time
12+
1113load_dotenv ()
1214
1315driver = config .ODBC_DRIVER
@@ -33,33 +35,47 @@ def dict_cursor(cursor):
3335
3436
3537def get_connection ():
36- try :
37- credential = DefaultAzureCredential ( managed_identity_client_id = mid_id )
38+ max_retries = 5
39+ retry_delay = 2
3840
39- token_bytes = credential .get_token (
40- "https://database.windows.net/.default"
41- ).token .encode ("utf-16-LE" )
42- token_struct = struct .pack (
43- f"<I{ len (token_bytes )} s" , len (token_bytes ), token_bytes
44- )
45- SQL_COPT_SS_ACCESS_TOKEN = (
46- 1256 # This connection option is defined by Microsoft in msodbcsql.h
47- )
41+ for attempt in range (max_retries ):
42+ try :
43+ credential = DefaultAzureCredential (managed_identity_client_id = mid_id )
4844
49- # Set up the connection
50- connection_string = f"DRIVER={ driver } ;SERVER={ server } ;DATABASE={ database } ;"
51- conn = pyodbc .connect (
52- connection_string , attrs_before = {SQL_COPT_SS_ACCESS_TOKEN : token_struct }
53- )
54- return conn
55- except pyodbc .Error as e :
56- logging .error (f"Failed with Default Credential: { str (e )} " )
57- conn = pyodbc .connect (
58- f"DRIVER={ driver } ;SERVER={ server } ;DATABASE={ database } ;UID={ username } ;PWD={ password } " ,
59- timeout = 5 ,
60- )
61- logging .info ("Connected using Username & Password" )
62- return conn
45+ token_bytes = credential .get_token (
46+ "https://database.windows.net/.default"
47+ ).token .encode ("utf-16-LE" )
48+ token_struct = struct .pack (
49+ f"<I{ len (token_bytes )} s" , len (token_bytes ), token_bytes
50+ )
51+ SQL_COPT_SS_ACCESS_TOKEN = (
52+ 1256 # This connection option is defined by Microsoft in msodbcsql.h
53+ )
54+
55+ # Set up the connection
56+ connection_string = f"DRIVER={ driver } ;SERVER={ server } ;DATABASE={ database } ;"
57+ conn = pyodbc .connect (
58+ connection_string , attrs_before = {SQL_COPT_SS_ACCESS_TOKEN : token_struct }
59+ )
60+ return conn
61+ except pyodbc .Error as e :
62+ logging .error (f"Failed with Default Credential: { str (e )} " )
63+ try :
64+ conn = pyodbc .connect (
65+ f"DRIVER={ driver } ;SERVER={ server } ;DATABASE={ database } ;UID={ username } ;PWD={ password } " ,
66+ timeout = 5 ,
67+ )
68+ logging .info ("Connected using Username & Password" )
69+ return conn
70+ except pyodbc .Error as e :
71+ logging .error (f"Failed with Username & Password: { str (e )} " )
72+
73+ if attempt < max_retries - 1 :
74+ logging .info (f"Retrying in { retry_delay } seconds..." )
75+ time .sleep (retry_delay )
76+ retry_delay *= 2 # Exponential backoff
77+ else :
78+ raise e
6379
6480
6581def get_client_name_from_db (client_id : str ) -> str :
0 commit comments