|
| 1 | +import logging |
| 2 | +import traceback |
| 3 | +import json |
| 4 | + |
| 5 | +from functools import wraps |
| 6 | + |
| 7 | +def json_handler(func): |
| 8 | + @wraps(func) |
| 9 | + def wrapper(*args, **kwargs): |
| 10 | + decorated = json_exception_handler(json_payload_extractor(func)) |
| 11 | + return decorated(*args, **kwargs) |
| 12 | + return wrapper |
| 13 | + |
| 14 | + |
| 15 | +def json_payload_extractor(func): |
| 16 | + @wraps(func) |
| 17 | + def wrapper(self, in_string): |
| 18 | + try: |
| 19 | + request = json.loads(in_string) |
| 20 | + kwargs = {'request': request, 'in_string': in_string} |
| 21 | + if 'payload' in request: |
| 22 | + # if request contains payload, parse it and add it as payload parameter |
| 23 | + kwargs['payload'] = json.loads(request['payload']) |
| 24 | + if 'query' in request: |
| 25 | + # if request contains query, parse it and add it as query parameter |
| 26 | + kwargs['query'] = _convert_tuples_to_dict(request['query']) |
| 27 | + return func(self, **kwargs) |
| 28 | + except ValueError as e: |
| 29 | + return {'payload': {'success': 'false', 'result': f'Error parsing JSON: {e}'}, |
| 30 | + 'status': 400 |
| 31 | + } |
| 32 | + return wrapper |
| 33 | + |
| 34 | + |
| 35 | +def json_exception_handler(func): |
| 36 | + @wraps(func) |
| 37 | + def wrapper(*args, **kwargs): |
| 38 | + try: |
| 39 | + return func(*args, **kwargs) |
| 40 | + except Exception as e: |
| 41 | + logging.error( |
| 42 | + f'error={repr(e)} traceback={traceback.format_exc()}') |
| 43 | + return {'payload': {'success': 'false', 'message': f'Error: {repr(e)}'}, |
| 44 | + 'status': 500 |
| 45 | + } |
| 46 | + return wrapper |
| 47 | + |
| 48 | + |
| 49 | +def _convert_tuples_to_dict(tuples): |
| 50 | + return {t[0]: t[1] for t in tuples} |
| 51 | + |
0 commit comments