From fc9221d0b328476d1e469388b0405b90ffe799c3 Mon Sep 17 00:00:00 2001 From: psyray Date: Tue, 8 Oct 2024 16:53:51 +0200 Subject: [PATCH] feat: enhance IP retrieval with caching - Implemented caching for external IP retrieval in the misc function to reduce unnecessary requests and improve performance. - Added error handling and logging for external IP retrieval failures. --- web/reNgine/context_processors.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/web/reNgine/context_processors.py b/web/reNgine/context_processors.py index 8a998c3e..f9f08c6d 100644 --- a/web/reNgine/context_processors.py +++ b/web/reNgine/context_processors.py @@ -1,11 +1,29 @@ from . import settings import requests +from django.core.cache import cache +import logging + +logger = logging.getLogger(__name__) def version(request): return {"RENGINE_CURRENT_VERSION": settings.RENGINE_CURRENT_VERSION} def misc(request): - externalIp = requests.get('https://checkip.amazonaws.com').text.strip() + # Attempt to retrieve the external IP address from the cache + external_ip = cache.get('external_ip') + + if external_ip is None: + try: + # If the IP address is not in the cache, make the request + external_ip = requests.get('https://checkip.amazonaws.com').text.strip() + # Cache the IP address for 1 hour (3600 seconds) + cache.set('external_ip', external_ip, timeout=3600) + except requests.RequestException as e: + # Handle the exception if the request fails + external_ip = 'Unable to retrieve IP' # Default value in case of error + # You can also log the error if necessary + logger.error(f"Error retrieving external IP: {e}") + return { - 'external_ip': externalIp + 'external_ip': external_ip } \ No newline at end of file