|
25 | 25 | parser = reqparse.RequestParser() |
26 | 26 | parser.add_argument('customer') |
27 | 27 |
|
28 | | -# Implement manual connection pooling |
29 | | -class ConnectionManager(object): |
30 | | - __instance = None |
31 | | - __conn_index = 0 |
32 | | - __conn_dict = {} |
33 | | - __lock = Lock() |
34 | | - |
35 | | - def __new__(cls): |
36 | | - if ConnectionManager.__instance is None: |
37 | | - ConnectionManager.__instance = object.__new__(cls) |
38 | | - return ConnectionManager.__instance |
39 | | - |
40 | | - def getConnection(self): |
41 | | - self.__lock.acquire() |
42 | | - self.__conn_index += 1 |
43 | | - |
44 | | - if self.__conn_index > 9: |
45 | | - self.__conn_index = 0 |
46 | | - |
47 | | - if not self.__conn_index in self.__conn_dict.keys(): |
48 | | - application_name = ";APP={0}-{1}".format(socket.gethostname(), self.__conn_index) |
49 | | - conn = pyodbc.connect(os.environ['SQLAZURECONNSTR_WWIF'] + application_name) |
50 | | - self.__conn_dict.update( { self.__conn_index: conn } ) |
51 | | - |
52 | | - result = self.__conn_dict[self.__conn_index] |
53 | | - self.__lock.release() |
54 | | - |
55 | | - return result |
56 | | - |
57 | 28 | class Queryable(Resource): |
58 | 29 | def executeQueryJson(self, verb, payload=None): |
59 | 30 | result = {} |
60 | | - conn = ConnectionManager().getConnection() |
61 | | - cursor = conn.cursor() |
62 | | - entity = type(self).__name__.lower() |
63 | | - procedure = f"web.{verb}_{entity}" |
64 | | - try: |
65 | | - if payload: |
66 | | - cursor.execute(f"EXEC {procedure} ?", json.dumps(payload)) |
67 | | - else: |
68 | | - cursor.execute(f"EXEC {procedure}") |
69 | | - |
70 | | - result = cursor.fetchone() |
71 | | - |
72 | | - if result: |
73 | | - result = json.loads(result[0]) |
74 | | - else: |
75 | | - result = {} |
76 | | - |
77 | | - cursor.commit() |
78 | | - except: |
79 | | - print("Unexpected error:", sys.exc_info()[0]) |
80 | | - raise |
81 | | - finally: |
82 | | - cursor.close() |
| 31 | + with pyodbc.connect(os.environ['SQLAZURECONNSTR_WWIF']) as conn: |
| 32 | + cursor = conn.cursor() |
| 33 | + entity = type(self).__name__.lower() |
| 34 | + procedure = f"web.{verb}_{entity}" |
| 35 | + try: |
| 36 | + if payload: |
| 37 | + cursor.execute(f"EXEC {procedure} ?", json.dumps(payload)) |
| 38 | + else: |
| 39 | + cursor.execute(f"EXEC {procedure}") |
| 40 | + |
| 41 | + result = cursor.fetchone() |
| 42 | + |
| 43 | + if result: |
| 44 | + result = json.loads(result[0]) |
| 45 | + else: |
| 46 | + result = {} |
| 47 | + |
| 48 | + cursor.commit() |
| 49 | + except: |
| 50 | + conn.close() |
| 51 | + raise |
| 52 | + finally: |
| 53 | + cursor.close() |
83 | 54 |
|
84 | 55 | return result |
85 | 56 |
|
|
0 commit comments