manejo del get

parent d282e884
......@@ -586,93 +586,58 @@ import requests
from django.http import JsonResponse, HttpResponseNotAllowed
from django.core.management import call_command
from django.views.decorators.csrf import csrf_exempt
import os
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
import subprocess
@csrf_exempt
def run_update_and_report(request):
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
# Inicializar variables para recopilar resultados y errores
results = {
'status': 'success',
'messages': [],
'errors': [],
'api_response': None
}
status_code = 200
try:
# Leer y validar JSON del request
try:
data = json.loads(request.body)
except json.JSONDecodeError as e:
results['status'] = 'partial_success'
results['errors'].append('JSON inválido')
status_code = 400
data = {} # Usar valores por defecto
db_path = data.get('db_path', '/data/m3/news/')
json_output_path = data.get('output_path', 'catalog/static/js/data.js')
# Ejecutar updateDB
try:
call_command('updateDB', db_path)
results['messages'].append('updateDB ejecutado correctamente')
except Exception as e:
results['status'] = 'partial_success'
results['errors'].append(f'Error en updateDB: {str(e)}')
# No hacemos return, continuamos con el siguiente comando
# Ejecutar report
try:
call_command('report', json_output_path)
results['messages'].append(f'Reporte generado en {json_output_path}')
except Exception as e:
results['status'] = 'partial_success'
results['errors'].append(f'Error en report: {str(e)}')
# Obtener la última fecha de ejecución
return JsonResponse({'status': 'error', 'message': 'Only POST requests are allowed'}, status=405)
# Get the base directory (where manage.py is located)
base_dir = settings.BASE_DIR
script_path = os.path.join(base_dir, 'update.sh')
# Check if the script exists
if not os.path.exists(script_path):
return JsonResponse({'status': 'error', 'message': 'update.sh not found'}, status=404)
# Check if the script is executable
if not os.access(script_path, os.X_OK):
try:
last_execution_date = read_last_execution_date() or datetime.date.today().strftime('%Y-%m-%d')
fecha_inicio = last_execution_date
fecha_final = (datetime.date.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
os.chmod(script_path, 0o755) # Make the script executable
except Exception as e:
results['status'] = 'partial_success'
results['errors'].append(f'Error al leer fecha de ejecución: {str(e)}')
# Usar fechas por defecto si hay error
fecha_inicio = datetime.date.today().strftime('%Y-%m-%d')
fecha_final = (datetime.date.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
# Enviar solicitud POST a API externa
try:
payload = {"fecha_inicio": fecha_inicio, "fecha_final": fecha_final}
response = requests.post("https://em.geoint.mx/m3/processnews", json=payload, timeout=10)
response.raise_for_status()
results['api_response'] = response.json()
results['messages'].append('API externa llamada correctamente')
except requests.exceptions.RequestException as e:
results['status'] = 'partial_success'
results['errors'].append(f'Error en API externa: {str(e)}')
# Guardar nueva fecha de ejecución
try:
write_execution_date()
results['messages'].append('Fecha de ejecución actualizada')
except Exception as e:
results['status'] = 'partial_success'
results['errors'].append(f'Error al escribir fecha de ejecución: {str(e)}')
return JsonResponse({'status': 'error', 'message': f'Cannot make script executable: {str(e)}'}, status=500)
try:
# Run the script and capture output
result = subprocess.run(
[script_path],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
output = {
'status': 'success',
'return_code': result.returncode,
'stdout': result.stdout,
'stderr': result.stderr
}
return JsonResponse(output)
except subprocess.CalledProcessError as e:
return JsonResponse({
'status': 'error',
'message': 'Script execution failed',
'return_code': e.returncode,
'stdout': e.stdout,
'stderr': e.stderr
}, status=500)
except Exception as e:
# Este bloque captura errores inesperados no manejados en los bloques try internos
print(traceback.format_exc())
results['status'] = 'error'
results['errors'].append(f'Error inesperado: {str(e)}')
status_code = 500
# Determinar el código de estado final
if results['status'] == 'error':
status_code = 500
elif results['status'] == 'partial_success' and status_code == 200:
status_code = 207 # Multi-Status, si todo fue parcial
return JsonResponse(results, status=status_code)
\ No newline at end of file
return JsonResponse({'status': 'error', 'message': str(e)}, status=500)
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment