@@ -48,33 +48,40 @@ def on_get(req, resp):
4848 resp: Falcon response object
4949 """
5050 admin_control (req )
51- cnx = mysql .connector .connect (** config .myems_user_db )
52- cursor = cnx .cursor ()
53-
54- # Query to retrieve all API keys
55- query = (" SELECT id, name, token, created_datetime_utc, expires_datetime_utc "
56- " FROM tbl_api_keys " )
57- cursor .execute (query )
58- rows = cursor .fetchall ()
59-
60- # Build result list with timezone conversion
61- token_list = list ()
62- if rows is not None and len (rows ) > 0 :
63- timezone_offset = int (config .utc_offset [1 :3 ]) * 60 + int (config .utc_offset [4 :6 ])
64- if config .utc_offset [0 ] == '-' :
65- timezone_offset = - timezone_offset
66- for row in rows :
67- token_list .append ({"id" : row [0 ],
68- "name" : row [1 ],
69- "token" : row [2 ],
70- "created_datetime" : (row [3 ].replace (tzinfo = timezone .utc )
71- + timedelta (minutes = timezone_offset )).isoformat ()[0 :19 ],
72- "expires_datetime" : (row [4 ].replace (tzinfo = timezone .utc )
73- + timedelta (minutes = timezone_offset )).isoformat ()[0 :19 ]})
74-
75- cursor .close ()
76- cnx .close ()
77- resp .text = json .dumps (token_list )
51+ cnx = None
52+ try :
53+ cnx = mysql .connector .connect (** config .myems_user_db )
54+ cursor = None
55+ try :
56+ cursor = cnx .cursor ()
57+ # Query to retrieve all API keys
58+ query = (" SELECT id, name, token, created_datetime_utc, expires_datetime_utc "
59+ " FROM tbl_api_keys " )
60+ cursor .execute (query )
61+ rows = cursor .fetchall ()
62+
63+ # Build result list with timezone conversion
64+ token_list = list ()
65+ if rows is not None and len (rows ) > 0 :
66+ timezone_offset = int (config .utc_offset [1 :3 ]) * 60 + int (config .utc_offset [4 :6 ])
67+ if config .utc_offset [0 ] == '-' :
68+ timezone_offset = - timezone_offset
69+ for row in rows :
70+ token_list .append ({"id" : row [0 ],
71+ "name" : row [1 ],
72+ "token" : row [2 ],
73+ "created_datetime" : (row [3 ].replace (tzinfo = timezone .utc )
74+ + timedelta (minutes = timezone_offset )).isoformat ()[0 :19 ],
75+ "expires_datetime" : (row [4 ].replace (tzinfo = timezone .utc )
76+ + timedelta (minutes = timezone_offset )).isoformat ()[0 :19 ]})
77+
78+ resp .text = json .dumps (token_list )
79+ finally :
80+ if cursor is not None :
81+ cursor .close ()
82+ finally :
83+ if cnx is not None :
84+ cnx .close ()
7885
7986 @staticmethod
8087 def on_post (req , resp ):
@@ -129,32 +136,36 @@ def on_post(req, resp):
129136
130137 # Generate secure random token
131138 token = hashlib .sha512 (os .urandom (16 )).hexdigest ()
132- cnx = mysql .connector .connect (** config .myems_user_db )
133- cursor = cnx .cursor ()
134-
135- # Check if API key name already exists
136- cursor .execute (" SELECT name FROM tbl_api_keys"
137- " WHERE name = %s " , (name ,))
138- rows = cursor .fetchall ()
139-
140- if rows is not None and len (rows ) > 0 :
141- cursor .close ()
142- cnx .close ()
143- raise falcon .HTTPError (status = falcon .HTTP_400 , title = 'API.ERROR' ,
144- description = 'API.API_KEY_NAME_IS_ALREADY_IN_USE' )
145-
146- # Insert new API key into database
147- cursor .execute (" INSERT INTO tbl_api_keys "
148- " (name, token, created_datetime_utc, expires_datetime_utc) "
149- " VALUES(%s, %s, %s, %s) " , (name , token , datetime .utcnow (), expires_datetime_utc ))
150-
151- new_id = cursor .lastrowid
152- cnx .commit ()
153- cursor .close ()
154- cnx .close ()
155-
156- resp .status = falcon .HTTP_201
157- resp .location = '/apikeys/' + str (new_id )
139+ cnx = None
140+ try :
141+ cnx = mysql .connector .connect (** config .myems_user_db )
142+ cursor = None
143+ try :
144+ cursor = cnx .cursor ()
145+ # Check if API key name already exists
146+ cursor .execute (" SELECT name FROM tbl_api_keys"
147+ " WHERE name = %s " , (name ,))
148+ rows = cursor .fetchall ()
149+
150+ if rows is not None and len (rows ) > 0 :
151+ raise falcon .HTTPError (status = falcon .HTTP_400 , title = 'API.ERROR' ,
152+ description = 'API.API_KEY_NAME_IS_ALREADY_IN_USE' )
153+
154+ # Insert new API key into database
155+ cursor .execute (" INSERT INTO tbl_api_keys "
156+ " (name, token, created_datetime_utc, expires_datetime_utc) "
157+ " VALUES(%s, %s, %s, %s) " , (name , token , datetime .utcnow (), expires_datetime_utc ))
158+
159+ new_id = cursor .lastrowid
160+ cnx .commit ()
161+ resp .status = falcon .HTTP_201
162+ resp .location = '/apikeys/' + str (new_id )
163+ finally :
164+ if cursor is not None :
165+ cursor .close ()
166+ finally :
167+ if cnx is not None :
168+ cnx .close ()
158169
159170
160171class ApiKeyItem :
@@ -205,35 +216,40 @@ def on_get(req, resp, id_):
205216 raise falcon .HTTPError (status = falcon .HTTP_400 ,
206217 title = "API.INVALID_API_KEY_ID" )
207218
208- cnx = mysql .connector .connect (** config .myems_user_db )
209- cursor = cnx .cursor ()
210-
211- # Query to retrieve specific API key by ID
212- query = (" SELECT id, name, token, created_datetime_utc, expires_datetime_utc "
213- " FROM tbl_api_keys "
214- " WHERE id = %s " )
215- cursor .execute (query , (id_ ,))
216- row = cursor .fetchone ()
217- cursor .close ()
218- cnx .close ()
219-
220- if row is None :
221- raise falcon .HTTPError (status = falcon .HTTP_404 , title = 'API.NOT_FOUND' ,
222- description = 'API.API_KEY_NOT_FOUND' )
223- else :
224- # Convert UTC datetime to local timezone
225- timezone_offset = int (config .utc_offset [1 :3 ]) * 60 + int (config .utc_offset [4 :6 ])
226- if config .utc_offset [0 ] == '-' :
227- timezone_offset = - timezone_offset
228- meta_result = {"id" : row [0 ],
229- "name" : row [1 ],
230- "token" : row [2 ],
231- "created_datetime" : (row [3 ].replace (tzinfo = timezone .utc ) +
232- timedelta (minutes = timezone_offset )).isoformat ()[0 :19 ],
233- "expires_datetime" : (row [4 ].replace (tzinfo = timezone .utc ) +
234- timedelta (minutes = timezone_offset )).isoformat ()[0 :19 ]}
235-
236- resp .text = json .dumps (meta_result )
219+ cnx = None
220+ try :
221+ cnx = mysql .connector .connect (** config .myems_user_db )
222+ cursor = None
223+ try :
224+ cursor = cnx .cursor ()
225+ # Query to retrieve specific API key by ID
226+ query = (" SELECT id, name, token, created_datetime_utc, expires_datetime_utc "
227+ " FROM tbl_api_keys "
228+ " WHERE id = %s " )
229+ cursor .execute (query , (id_ ,))
230+ row = cursor .fetchone ()
231+
232+ if row is None :
233+ raise falcon .HTTPError (status = falcon .HTTP_404 , title = 'API.NOT_FOUND' ,
234+ description = 'API.API_KEY_NOT_FOUND' )
235+ # Convert UTC datetime to local timezone
236+ timezone_offset = int (config .utc_offset [1 :3 ]) * 60 + int (config .utc_offset [4 :6 ])
237+ if config .utc_offset [0 ] == '-' :
238+ timezone_offset = - timezone_offset
239+ meta_result = {"id" : row [0 ],
240+ "name" : row [1 ],
241+ "token" : row [2 ],
242+ "created_datetime" : (row [3 ].replace (tzinfo = timezone .utc ) +
243+ timedelta (minutes = timezone_offset )).isoformat ()[0 :19 ],
244+ "expires_datetime" : (row [4 ].replace (tzinfo = timezone .utc ) +
245+ timedelta (minutes = timezone_offset )).isoformat ()[0 :19 ]}
246+ resp .text = json .dumps (meta_result )
247+ finally :
248+ if cursor is not None :
249+ cursor .close ()
250+ finally :
251+ if cnx is not None :
252+ cnx .close ()
237253
238254 @staticmethod
239255 def on_put (req , resp , id_ ):
@@ -300,40 +316,41 @@ def on_put(req, resp, id_):
300316 raise falcon .HTTPError (status = falcon .HTTP_400 , title = 'API.BAD_REQUEST' ,
301317 description = "API.INVALID_EXPIRES_DATETIME" )
302318
303- cnx = mysql .connector .connect (** config .myems_user_db )
304- cursor = cnx .cursor ()
305-
306- # Check if new name conflicts with existing API keys
307- cursor .execute (" SELECT name "
308- " FROM tbl_api_keys "
309- " WHERE name = %s " , (name ,))
310- if cursor .fetchall () is not None and \
311- len (cursor .fetchall ()) > 0 :
312- cursor .close ()
313- cnx .close ()
314- raise falcon .HTTPError (status = falcon .HTTP_404 , title = 'API.NOT_FOUND' ,
315- description = 'API.API_KEY_NAME_IS_ALREADY_IN_USE' )
316-
317- # Check if API key exists
318- cursor .execute (" SELECT token "
319- " FROM tbl_api_keys "
320- " WHERE id = %s " , (id_ ,))
321- if cursor .fetchone () is None :
322- cursor .close ()
323- cnx .close ()
324- raise falcon .HTTPError (status = falcon .HTTP_404 , title = 'API.NOT_FOUND' ,
325- description = 'API.API_KEY_NOT_FOUND' )
326-
327- # Update API key information
328- cursor .execute (" UPDATE tbl_api_keys "
329- " SET name = %s, expires_datetime_utc = %s "
330- " WHERE id = %s " , (name , expires_datetime_utc , id_ ))
331- cnx .commit ()
332-
333- cursor .close ()
334- cnx .close ()
335-
336- resp .status = falcon .HTTP_200
319+ cnx = None
320+ try :
321+ cnx = mysql .connector .connect (** config .myems_user_db )
322+ cursor = None
323+ try :
324+ cursor = cnx .cursor ()
325+ # Check if new name conflicts with existing API keys
326+ cursor .execute (" SELECT name "
327+ " FROM tbl_api_keys "
328+ " WHERE name = %s " , (name ,))
329+ name_rows = cursor .fetchall ()
330+ if name_rows is not None and len (name_rows ) > 0 :
331+ raise falcon .HTTPError (status = falcon .HTTP_404 , title = 'API.NOT_FOUND' ,
332+ description = 'API.API_KEY_NAME_IS_ALREADY_IN_USE' )
333+
334+ # Check if API key exists
335+ cursor .execute (" SELECT token "
336+ " FROM tbl_api_keys "
337+ " WHERE id = %s " , (id_ ,))
338+ if cursor .fetchone () is None :
339+ raise falcon .HTTPError (status = falcon .HTTP_404 , title = 'API.NOT_FOUND' ,
340+ description = 'API.API_KEY_NOT_FOUND' )
341+
342+ # Update API key information
343+ cursor .execute (" UPDATE tbl_api_keys "
344+ " SET name = %s, expires_datetime_utc = %s "
345+ " WHERE id = %s " , (name , expires_datetime_utc , id_ ))
346+ cnx .commit ()
347+ resp .status = falcon .HTTP_200
348+ finally :
349+ if cursor is not None :
350+ cursor .close ()
351+ finally :
352+ if cnx is not None :
353+ cnx .close ()
337354
338355 @staticmethod
339356 def on_delete (req , resp , id_ ):
@@ -353,24 +370,27 @@ def on_delete(req, resp, id_):
353370 raise falcon .HTTPError (status = falcon .HTTP_400 , title = 'API.BAD_REQUEST' ,
354371 description = 'API.INVALID_API_KEY_ID' )
355372
356- cnx = mysql .connector .connect (** config .myems_user_db )
357- cursor = cnx .cursor ()
358-
359- # Check if API key exists before deletion
360- cursor .execute (" SELECT token "
361- " FROM tbl_api_keys "
362- " WHERE id = %s " , (id_ ,))
363- if cursor .fetchone () is None :
364- cursor .close ()
365- cnx .close ()
366- raise falcon .HTTPError (status = falcon .HTTP_404 , title = 'API.NOT_FOUND' ,
367- description = 'API.API_KEY_NOT_FOUND' )
368-
369- # Delete the API key
370- cursor .execute (" DELETE FROM tbl_api_keys WHERE id = %s " , (id_ ,))
371- cnx .commit ()
372-
373- cursor .close ()
374- cnx .close ()
375-
376- resp .status = falcon .HTTP_204
373+ cnx = None
374+ try :
375+ cnx = mysql .connector .connect (** config .myems_user_db )
376+ cursor = None
377+ try :
378+ cursor = cnx .cursor ()
379+ # Check if API key exists before deletion
380+ cursor .execute (" SELECT token "
381+ " FROM tbl_api_keys "
382+ " WHERE id = %s " , (id_ ,))
383+ if cursor .fetchone () is None :
384+ raise falcon .HTTPError (status = falcon .HTTP_404 , title = 'API.NOT_FOUND' ,
385+ description = 'API.API_KEY_NOT_FOUND' )
386+
387+ # Delete the API key
388+ cursor .execute (" DELETE FROM tbl_api_keys WHERE id = %s " , (id_ ,))
389+ cnx .commit ()
390+ resp .status = falcon .HTTP_204
391+ finally :
392+ if cursor is not None :
393+ cursor .close ()
394+ finally :
395+ if cnx is not None :
396+ cnx .close ()
0 commit comments