import json from urllib.error import HTTPError, URLError from urllib.request import Request, urlopen from django.http import HttpResponse, JsonResponse from django.shortcuts import render from django.views import View from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from ingest.constants import API_KEY, API_TARGET_URL, STATIC_SENSOR_PAYLOAD class SensorSimulatorAppView(View): def get(self, request): return render( request, "ingest/index.html", { "default_payload": json.dumps(STATIC_SENSOR_PAYLOAD, indent=2), "default_url": API_TARGET_URL, "default_api_key": API_KEY, }, ) @method_decorator(csrf_exempt, name="dispatch") class ForwardSensorDataView(View): def post(self, request): target_url = request.POST.get("target_url", "").strip() api_key = request.POST.get("api_key", "").strip() if not target_url: return JsonResponse({"error": "target_url is required"}, status=400) if not api_key: return JsonResponse({"error": "api_key is required"}, status=400) payload = STATIC_SENSOR_PAYLOAD body = json.dumps(payload).encode("utf-8") outbound_request = Request( target_url, data=body, headers={ "Content-Type": "application/json", "api_key": api_key, }, method="POST", ) try: with urlopen(outbound_request, timeout=15) as response: response_body = response.read().decode("utf-8") content_type = response.headers.get("Content-Type", "") parsed_body = response_body if "application/json" in content_type and response_body: parsed_body = json.loads(response_body) return JsonResponse( { "status": response.status, "sent_headers": { "Content-Type": "application/json", "api_key": api_key, }, "sent_payload": payload, "response": parsed_body, } ) except HTTPError as exc: error_body = exc.read().decode("utf-8", errors="replace") return JsonResponse( { "error": "upstream returned an error", "status": exc.code, "sent_headers": { "Content-Type": "application/json", "api_key": api_key, }, "sent_payload": payload, "response": error_body, }, status=502, ) except URLError as exc: return JsonResponse( { "error": "could not reach upstream api", "details": str(exc.reason), "sent_headers": { "Content-Type": "application/json", "api_key": api_key, }, "sent_payload": payload, }, status=502, ) return HttpResponse(status=500)