Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 29e53e0

Browse files
committed
removed global variable and used singleton pattern
1 parent d2b9ef8 commit 29e53e0

File tree

1 file changed

+27
-18
lines changed

1 file changed

+27
-18
lines changed

app.py

+27-18
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from flask_restful import reqparse, abort, Api, Resource
55
import json
66
import pyodbc
7+
import socket
78
from threading import Lock
89

910
# Initialize Flask
@@ -14,30 +15,38 @@
1415
parser = reqparse.RequestParser()
1516
parser.add_argument('customer')
1617

17-
conn_index = 0
18-
conn_list = list()
18+
class ConnectionManager(object):
19+
__instance = None
20+
__conn_index = 0
21+
__conn_dict = {}
22+
__lock = Lock()
1923

20-
for c in range(10):
21-
conn = pyodbc.connect(os.environ['SQLAZURECONNSTR_WWIF'])
22-
conn_list.append(conn)
24+
def __new__(cls):
25+
if ConnectionManager.__instance is None:
26+
ConnectionManager.__instance = object.__new__(cls)
27+
return ConnectionManager.__instance
2328

24-
lock = Lock()
29+
def getConnection(self):
30+
self.__lock.acquire()
31+
self.__conn_index += 1
32+
33+
if self.__conn_index > 9:
34+
self.__conn_index = 0
2535

26-
def getConnection():
27-
global conn_index
28-
29-
lock.acquire()
30-
conn_index += 1
31-
lock.release()
32-
33-
if conn_index > 9:
34-
conn_index = 0
35-
return conn_list[conn_index]
36+
if not self.__conn_index in self.__conn_dict.keys():
37+
application_name = ";APP={0}-{1}".format(socket.gethostname(), self.__conn_index)
38+
conn = pyodbc.connect(os.environ['SQLAZURECONNSTR_WWIF'] + application_name)
39+
self.__conn_dict.update( { self.__conn_index: conn } )
40+
41+
result = self.__conn_dict[self.__conn_index]
42+
self.__lock.release()
43+
44+
return result
3645

3746
class Queryable(Resource):
3847
def executeQueryJson(self, verb, payload=None):
39-
result = {}
40-
conn = getConnection()
48+
result = {}
49+
conn = ConnectionManager().getConnection()
4150
cursor = conn.cursor()
4251
entity = type(self).__name__.lower()
4352
procedure = f"web.{verb}_{entity}"

0 commit comments

Comments
 (0)