udistrital / core_documentacion

0 stars 0 forks source link

Implementar SDK para Python en utils_oas - Parte 2 #80

Closed diagutierrezro closed 1 month ago

diagutierrezro commented 1 month ago

Se requiere realizar la continuación de la implementación del SDK iniciado en #70, esta implementación debe incluir los metodos para inicializar X-Ray (initXRay), iniciar los segmentos, subsegmentos, finalizar segmentos, actualizarlos, etc. Similar a como se maneja el SDK para las Apis de Go que se encuentra en utils_oas

Sub Tareas

Criterios de aceptación

Requerimientos

No aplica

Definition of Ready - DoR

Definition of Done - DoD - Desarrollo

JulianAvella commented 1 month ago

Tomando como referencia el código realizado en go en el archivo "https://github.com/udistrital/utils_oas/blob/master/request/request_tools.go" para las peticiones http, se crean las mismas funciones generales y estandarizadas para el lenguaje python:

import requests import json import io import logging from aws_xray_sdk.core import xray_recorder

Configuración del logger

logging.basicConfig(level=logging.ERROR) logger = logging.getLogger(name)

global_header = ""

def set_header(header): global global_header global_header = header

def get_header(): return global_header

def send_json(url, method, target, datajson=None): headers = { "Authorization": get_header(), "Accept": "application/json", "Content-Type": "application/json" } segment = xray_recorder.begin_segment(name="send_json")

try:
    response = requests.request(method, url, json=datajson, headers=headers)
    response.raise_for_status()
    xray_recorder.end_segment()

    return response.json() if target is None else json.loads(response.text, object_hook=target)
except requests.RequestException as e:
    logger.error(f"Error reading response: {e}")
    xray_recorder.end_segment()
    raise
except Exception as e:
    logger.error(f"Error processing request: {e}")
    xray_recorder.end_segment()
    raise

def send_json_escape_unicode(url, method, target, datajson=None): headers = { "Authorization": get_header(), "Accept": "application/json", "Content-Type": "application/json" } segment = xray_recorder.begin_segment(name="send_json_escape_unicode")

try:
    datajson = json.dumps(datajson, ensure_ascii=False) if datajson else None
    response = requests.request(method, url, data=datajson, headers=headers)
    response.raise_for_status()
    xray_recorder.end_segment()

    return response.json() if target is None else json.loads(response.text, object_hook=target)
except requests.RequestException as e:
    logger.error(f"Error reading response: {e}")
    xray_recorder.end_segment()
    raise
except Exception as e:
    logger.error(f"Error processing request: {e}")
    xray_recorder.end_segment()
    raise

def get_json(url, target): headers = { "Authorization": get_header(), "Accept": "application/json" } segment = xray_recorder.begin_segment(name="get_json")

try:
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    xray_recorder.end_segment()

    return response.json() if target is None else json.loads(response.text, object_hook=target)
except requests.RequestException as e:
    logger.error(f"Error reading response: {e}")
    xray_recorder.end_segment()
    raise
except Exception as e:
    logger.error(f"Error processing request: {e}")
    xray_recorder.end_segment()
    raise

def get_json_wso2(url, target): headers = { "Accept": "application/json" } segment = xray_recorder.begin_segment(name="get_json_wso2")

try:
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    xray_recorder.end_segment()

    return response.json() if target is None else json.loads(response.text, object_hook=target)
except requests.RequestException as e:
    logger.error(f"Error reading response: {e}")
    xray_recorder.end_segment()
    raise
except Exception as e:
    logger.error(f"Error processing request: {e}")
    xray_recorder.end_segment()
    raise

def get_json_test(url, target): headers = { "Accept": "application/json" } segment = xray_recorder.begin_segment(name="get_json_test")

try:
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    xray_recorder.end_segment()

    return response, json.loads(response.text, object_hook=target)
except requests.RequestException as e:
    logger.error(f"Error reading response: {e}")
    xray_recorder.end_segment()
    raise
except Exception as e:
    logger.error(f"Error processing request: {e}")
    xray_recorder.end_segment()
    raise

def get_xml(url, target): headers = { "Accept": "application/xml" } segment = xray_recorder.begin_segment(name="get_xml")

try:
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    xray_recorder.end_segment()

    return response.text if target is None else xml.loads(response.text, object_hook=target)
except requests.RequestException as e:
    logger.error(f"Error reading response: {e}")
    xray_recorder.end_segment()
    raise
except Exception as e:
    logger.error(f"Error processing request: {e}")
    xray_recorder.end_segment()
    raise

def get_xml2string(url): headers = { "Accept": "application/xml" } segment = xray_recorder.begin_segment(name="get_xml2string")

try:
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    xray_recorder.end_segment()

    return response.text.strip()
except requests.RequestException as e:
    logger.error(f"Error reading response: {e}")
    xray_recorder.end_segment()
    raise
except Exception as e:
    logger.error(f"Error processing request: {e}")
    xray_recorder.end_segment()
    raise
JulianAvella commented 1 month ago

Se hace la implementación en la api llamada gestor_documental_mid, y dentro se crea una carpeta xray y dentro tiene dos archivos, uno llamado xray.py que tiene la configuración del sdk de xray y el segundo archivo llamado request_tools.py que tiene las funciones generalizadas para las peticiones http con la llamada del archivo de configuración de xray, entonces para inicializar xray en la api se modifica el archivo de inicio llamado api.py y queda así: import os from flask import Flask from conf import conf from routers import router from controllers import error from xray.xray import init_xray conf.checkEnv()

nuxeo = conf.init_nuxeo() app = Flask(name)

Inicializamos X-Ray init_xray(app)

router.addRouting(app, nuxeo) error.add_error_handler(app)

print(app.url_map)

if name == 'main':

app.debug = True

app.run(host='0.0.0.0', port=int(os.environ['API_PORT'])) y el archivo llamado document.py que esta dentro de carpeta controllers, el cual hace peticiones http, y se comenta algunas llamadas http y se remplaza por las peticiones con xray del archivo request_tools: la petición get queda así; #res_doc_crud = requests.get(str(os.environ['DOCUMENTOS_CRUD_URL'])+'/documento?query=Activo:true,Enlace:'+uid) url = str(os.environ['DOCUMENTOS_CRUD_URL']) + '/documento?query=Activo:true,Enlace:' + uid y la petición post queda así: #resPost = requests.post(str(os.environ['DOCUMENTOS_CRUD_URL'])+'/documento', json=DicPostDoc).content resPost = post_json(str(os.environ['DOCUMENTOS_CRUD_URL']) + '/documento', DicPostDoc)

Falta hacer unas pruebas con datos para las peticiones http y si en aws se reconoce la configuración del xray

diagutierrezro commented 1 month ago

Buen trabajo Julian, las pruebas y ajustes se trabajaran en otras issues.