gateway_placeholder/gateway/api/commonForAllServices.py

114 lines
4.7 KiB
Python

import os
import requests
from django.http import JsonResponse
import json
from dotenv import load_dotenv
from django.views.decorators.csrf import csrf_exempt
# Load environment variables
load_dotenv(override=True)
def get_base_url(service_name):
service_urls = {
# Update this dictionary based on your microservices
'testService': os.getenv("TEST_SERVICE_HOST"),
}
if service_name in service_urls:
return service_urls[service_name]
else:
raise ValueError(f"Invalid service name: {service_name}")
def make_request(method, url, headers, data=None):
try:
if method == 'GET':
response = requests.get(url, headers=headers, timeout=10)
elif method == 'POST':
response = requests.post(url, headers=headers, json=data, timeout=10)
elif method == 'PATCH':
response = requests.patch(url, headers=headers, json=data, timeout=10)
elif method == 'PUT':
response = requests.put(url, headers=headers, json=data, timeout=10)
elif method == 'DELETE':
response = requests.delete(url, headers=headers, timeout=10)
if response.status_code == 204:
return JsonResponse({'message': 'Successfully deleted'}, status=200)
# Return response based on status code
if 200 <= response.status_code < 300:
return JsonResponse(response.json(), safe=False, status=response.status_code)
return JsonResponse(response.json(), safe=False, status=response.status_code)
except requests.exceptions.Timeout:
return JsonResponse({'error': 'The request timed out. Please try again.'}, status=504)
except requests.exceptions.ConnectionError:
return JsonResponse({'error': 'Failed to connect to the external service. Please try again later.'}, status=502)
except requests.exceptions.RequestException as e:
return JsonResponse({'error': str(e)}, status=500)
@csrf_exempt
def handle_request(request, service_name, endpoint, id=None):
try:
base_url = get_base_url(service_name)
api_url = os.path.join(base_url, f'api/v1/{endpoint}/')
if id:
api_url = os.path.join(api_url, f'{id}/')
headers = {
'gateway-key': os.getenv("GATEWAY_KEY"),
'Content-Type': 'application/json',
}
# Forward the request to the external service
if request.method == 'GET':
return make_request('GET', api_url, headers)
elif request.method == 'POST':
json_data = json.loads(request.body) if request.body else None
return make_request('POST', api_url, headers, data=json_data)
elif request.method == 'PATCH' and id:
json_data = json.loads(request.body) if request.body else None
return make_request('PATCH', api_url, headers, data=json_data)
elif request.method == 'PUT' and id:
json_data = json.loads(request.body) if request.body else None
return make_request('PUT', api_url, headers, data=json_data)
elif request.method == 'DELETE' and id:
return make_request('DELETE', api_url, headers)
else:
return JsonResponse({'error': 'Invalid HTTP method'}, status=405)
except ValueError as e:
return JsonResponse({'error': str(e)}, status=400)
except Exception as e:
return JsonResponse({'error': 'An unexpected error occurred.'}, status=500)
@csrf_exempt
def custom_request(request, service_name, endpoint, payload=None, id=None):
try:
base_url = get_base_url(service_name)
api_url = os.path.join(base_url, f'api/v1/{endpoint}/')
if id:
api_url = os.path.join(api_url, f'{id}/')
headers = {
'gateway-key': os.getenv("GATEWAY_KEY"),
'Content-Type': 'application/json',
}
# Forward the request to the external service
if request.method == 'GET':
return make_request('GET', api_url, headers)
elif request.method == 'POST':
return make_request('POST', api_url, headers, data=payload)
elif request.method == 'PATCH' and id:
return make_request('PATCH', api_url, headers, data=payload)
elif request.method == 'PUT' and id:
return make_request('PUT', api_url, headers, data=payload)
elif request.method == 'DELETE' and id:
return make_request('DELETE', api_url, headers)
else:
return JsonResponse({'error': 'Invalid HTTP method'}, status=405)
except ValueError as e:
return JsonResponse({'error': str(e)}, status=400)
except Exception as e:
return JsonResponse({'error': 'An unexpected error occurred.'}, status=500)