| Conditions | 14 |
| Total Lines | 102 |
| Code Lines | 63 |
| Lines | 102 |
| Ratio | 100 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like core.protocol.ProtocolItem.on_put() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | from datetime import datetime, timedelta |
||
| 292 | View Code Duplication | @staticmethod |
|
| 293 | @user_logger |
||
| 294 | def on_put(req, resp, id_): |
||
| 295 | """ |
||
| 296 | Handle PUT requests to update a specific protocol |
||
| 297 | |||
| 298 | Updates the protocol with the specified ID. |
||
| 299 | Validates that the new name and code are unique. |
||
| 300 | |||
| 301 | Args: |
||
| 302 | req: Falcon request object containing updated protocol data: |
||
| 303 | - name: Updated protocol name (required) |
||
| 304 | - code: Updated protocol code (required) |
||
| 305 | resp: Falcon response object |
||
| 306 | id_: Protocol ID to update |
||
| 307 | """ |
||
| 308 | admin_control(req) |
||
| 309 | |||
| 310 | # Read and parse request body |
||
| 311 | try: |
||
| 312 | raw_json = req.stream.read().decode('utf-8') |
||
| 313 | except UnicodeDecodeError as ex: |
||
| 314 | print("Failed to decode request") |
||
| 315 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 316 | title='API.BAD_REQUEST', |
||
| 317 | description='API.INVALID_ENCODING') |
||
| 318 | except Exception as ex: |
||
| 319 | print("Unexpected error reading request stream") |
||
| 320 | raise falcon.HTTPError(status=falcon.HTTP_400, |
||
| 321 | title='API.BAD_REQUEST', |
||
| 322 | description='API.FAILED_TO_READ_REQUEST_STREAM') |
||
| 323 | |||
| 324 | # Validate protocol ID |
||
| 325 | if not id_.isdigit() or int(id_) <= 0: |
||
| 326 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 327 | description='API.INVALID_PROTOCOL_ID') |
||
| 328 | |||
| 329 | new_values = json.loads(raw_json) |
||
| 330 | |||
| 331 | # Validate protocol name |
||
| 332 | if 'name' not in new_values['data'].keys() or \ |
||
| 333 | not isinstance(new_values['data']['name'], str) or \ |
||
| 334 | len(str.strip(new_values['data']['name'])) == 0: |
||
| 335 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 336 | description='API.INVALID_PROTOCOL_NAME') |
||
| 337 | name = str.strip(new_values['data']['name']) |
||
| 338 | |||
| 339 | # Validate protocol code |
||
| 340 | if 'code' not in new_values['data'].keys() or \ |
||
| 341 | not isinstance(new_values['data']['code'], str) or \ |
||
| 342 | len(str.strip(new_values['data']['code'])) == 0: |
||
| 343 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 344 | description='API.INVALID_PROTOCOL_CODE') |
||
| 345 | code = str.strip(new_values['data']['code']) |
||
| 346 | |||
| 347 | # Connect to database |
||
| 348 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 349 | cursor = cnx.cursor() |
||
| 350 | |||
| 351 | # Check if protocol exists |
||
| 352 | cursor.execute(" SELECT name " |
||
| 353 | " FROM tbl_protocols " |
||
| 354 | " WHERE id = %s ", (id_,)) |
||
| 355 | if cursor.fetchone() is None: |
||
| 356 | cursor.close() |
||
| 357 | cnx.close() |
||
| 358 | raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 359 | description='API.PROTOCOL_NOT_FOUND') |
||
| 360 | |||
| 361 | # Check if new name already exists (excluding current protocol) |
||
| 362 | cursor.execute(" SELECT name " |
||
| 363 | " FROM tbl_protocols " |
||
| 364 | " WHERE name = %s AND id != %s ", (name, id_)) |
||
| 365 | if cursor.fetchone() is not None: |
||
| 366 | cursor.close() |
||
| 367 | cnx.close() |
||
| 368 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 369 | description='API.PROTOCOL_NAME_IS_ALREADY_IN_USE') |
||
| 370 | |||
| 371 | # Check if new code already exists (excluding current protocol) |
||
| 372 | cursor.execute(" SELECT code " |
||
| 373 | " FROM tbl_protocols " |
||
| 374 | " WHERE code = %s AND id != %s ", (code, id_)) |
||
| 375 | if cursor.fetchone() is not None: |
||
| 376 | cursor.close() |
||
| 377 | cnx.close() |
||
| 378 | raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 379 | description='API.PROTOCOL_CODE_IS_ALREADY_IN_USE') |
||
| 380 | |||
| 381 | # Update the protocol |
||
| 382 | update_row = (" UPDATE tbl_protocols " |
||
| 383 | " SET name = %s, code = %s " |
||
| 384 | " WHERE id = %s ") |
||
| 385 | cursor.execute(update_row, (name, |
||
| 386 | code, |
||
| 387 | id_,)) |
||
| 388 | cnx.commit() |
||
| 389 | |||
| 390 | cursor.close() |
||
| 391 | cnx.close() |
||
| 392 | |||
| 393 | resp.status = falcon.HTTP_200 |
||
| 394 | |||
| 397 |