Habia trabajado un buen poco pero como vi que tenia que separar los repositorios perdi bastante la historia :c
72 lines
1.8 KiB
Python
72 lines
1.8 KiB
Python
import logging
|
|
from collections import Mapping
|
|
|
|
_log = logging.getLogger('utils')
|
|
_log.addHandler(logging.NullHandler())
|
|
|
|
|
|
def pretty_print_json(json_input):
|
|
"""Formats and prints json to stdout with colors using pygments"""
|
|
import json
|
|
|
|
from pygments import highlight
|
|
from pygments.lexers import JsonLexer
|
|
from pygments.formatters import TerminalTrueColorFormatter
|
|
|
|
formatted_json = json.dumps(json_input, indent=2)
|
|
print(highlight(formatted_json, JsonLexer(), TerminalTrueColorFormatter()))
|
|
|
|
|
|
def message_response(status, error_message):
|
|
"""Sends an error response with the status code of the error and an explanation"""
|
|
from django.http import JsonResponse
|
|
|
|
json_message = {
|
|
'status_code': status,
|
|
'message': error_message
|
|
}
|
|
|
|
return JsonResponse(json_message, status=status)
|
|
|
|
|
|
# noinspection PyPep8Naming
|
|
def require_JSON(function):
|
|
"""Decorator to make a view only accept a json body"""
|
|
|
|
import functools
|
|
import json
|
|
|
|
@functools.wraps(function)
|
|
def decorator(*args, **kwargs):
|
|
try:
|
|
received_json = json.loads(args[0].body)
|
|
return function(*args, **kwargs, received_json=received_json)
|
|
except json.JSONDecodeError as error:
|
|
_log.warning(f'Function {function.__name__} got a non json request body')
|
|
return message_response(400, 'Se envío json no valido')
|
|
|
|
return decorator
|
|
|
|
|
|
def expected_keys(keys, dictionary):
|
|
for key in keys:
|
|
if key not in dictionary:
|
|
return f'No se encuentra {key}'
|
|
|
|
return None
|
|
|
|
|
|
def replace_key(json, old, new):
|
|
json[new] = json[old]
|
|
del json[old]
|
|
|
|
|
|
def sanitize_keys(json):
|
|
for key in list(json.keys()):
|
|
if '-' in key and key in json:
|
|
new_key = key.replace('-', '_')
|
|
replace_key(json, key, new_key)
|
|
return json
|
|
|
|
|