manejo del get

parent d282e884
...@@ -586,93 +586,58 @@ import requests ...@@ -586,93 +586,58 @@ import requests
from django.http import JsonResponse, HttpResponseNotAllowed from django.http import JsonResponse, HttpResponseNotAllowed
from django.core.management import call_command from django.core.management import call_command
from django.views.decorators.csrf import csrf_exempt 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 @csrf_exempt
def run_update_and_report(request): def run_update_and_report(request):
if request.method != 'POST': if request.method != 'POST':
return HttpResponseNotAllowed(['POST']) return JsonResponse({'status': 'error', 'message': 'Only POST requests are allowed'}, status=405)
# Inicializar variables para recopilar resultados y errores # Get the base directory (where manage.py is located)
results = { base_dir = settings.BASE_DIR
'status': 'success', script_path = os.path.join(base_dir, 'update.sh')
'messages': [],
'errors': [], # Check if the script exists
'api_response': None if not os.path.exists(script_path):
} return JsonResponse({'status': 'error', 'message': 'update.sh not found'}, status=404)
status_code = 200
# Check if the script is executable
try: if not os.access(script_path, os.X_OK):
# 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
try: try:
last_execution_date = read_last_execution_date() or datetime.date.today().strftime('%Y-%m-%d') os.chmod(script_path, 0o755) # Make the script executable
fecha_inicio = last_execution_date
fecha_final = (datetime.date.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
except Exception as e: except Exception as e:
results['status'] = 'partial_success' return JsonResponse({'status': 'error', 'message': f'Cannot make script executable: {str(e)}'}, status=500)
results['errors'].append(f'Error al leer fecha de ejecución: {str(e)}')
# Usar fechas por defecto si hay error try:
fecha_inicio = datetime.date.today().strftime('%Y-%m-%d') # Run the script and capture output
fecha_final = (datetime.date.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d') result = subprocess.run(
[script_path],
# Enviar solicitud POST a API externa check=True,
try: stdout=subprocess.PIPE,
payload = {"fecha_inicio": fecha_inicio, "fecha_final": fecha_final} stderr=subprocess.PIPE,
response = requests.post("https://em.geoint.mx/m3/processnews", json=payload, timeout=10) text=True
response.raise_for_status() )
results['api_response'] = response.json()
results['messages'].append('API externa llamada correctamente') output = {
except requests.exceptions.RequestException as e: 'status': 'success',
results['status'] = 'partial_success' 'return_code': result.returncode,
results['errors'].append(f'Error en API externa: {str(e)}') 'stdout': result.stdout,
'stderr': result.stderr
# Guardar nueva fecha de ejecución }
try: return JsonResponse(output)
write_execution_date()
results['messages'].append('Fecha de ejecución actualizada') except subprocess.CalledProcessError as e:
except Exception as e: return JsonResponse({
results['status'] = 'partial_success' 'status': 'error',
results['errors'].append(f'Error al escribir fecha de ejecución: {str(e)}') 'message': 'Script execution failed',
'return_code': e.returncode,
'stdout': e.stdout,
'stderr': e.stderr
}, status=500)
except Exception as e: except Exception as e:
# Este bloque captura errores inesperados no manejados en los bloques try internos return JsonResponse({'status': 'error', 'message': str(e)}, status=500)
print(traceback.format_exc()) \ No newline at end of file
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
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